2014-12-02 30 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

相關問題