2014-12-02 58 views
0

我不能在这个代码的错误处理:错误:`var`不活足够长的时间

extern crate serialize; 

use std::collections::TreeMap; 
use serialize::base64; 
use serialize::base64::{ToBase64, FromBase64}; 

fn main() { 
    method1(true); 
} 

fn method1(cond: bool) -> (&'static [u8], String) { 
    let ret1 = if cond { 
    let a = "a string in base64".as_bytes(); 
    let b = a.from_base64(); 
    let c = b.unwrap(); 
    let d = c.as_slice(); 
    d // error: `c` does not live long enough 


    // or 
    // "a string in base64".as_bytes().from_base64().unwrap().as_slice() - the same error 

    // or 
    // static a: &'static [u8] = &[1]; - no error, but that's not what I want 
    } else { 
    b"" 
    }; 

    (ret1, "aaa".to_string()) 
} 

如何摆脱它?

+0

可能重复的[但没有价值从它借来](http://stackoverflow.com/questions/27247142/but-there-is-no-value-for-it-to-be-借用)(这个理由仅在几个小时之前就已经包含在你的问题中) – 2014-12-02 22:17:14

回答

3

d是对在同一范围内创建的数据的引用,范围在if cond的大括号内。当您离开该范围时,数据已消失,那么参考d指向什么?这就是你得到错误的原因。您可以将其作为Vec<u8>退回,您已在c中拥有该文件。

+0

有什么方法可以从method1返回[u8]吗? – 2014-12-03 02:48:48

+0

@AlexanderSupertramp:No.'[u8]'是动态调整大小的,这意味着编译器不知道为返回值分配多少堆栈空间。这通常通过间接解决。这就是'Vec '在内部做的事情。 – sellibitze 2014-12-04 01:48:55