Rust 错误:`var`的寿命不够长
我无法处理此代码中的错误:Rust 错误:`var`的寿命不够长,rust,Rust,我无法处理此代码中的错误: 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 co
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())
}
如何摆脱它?
d
是对在同一范围内创建的数据的引用,该范围位于if cond
的括号内。当您离开该范围时,数据就消失了,那么引用d
指向什么?这就是为什么你会出错。您可以将其作为Vec
返回,您已经在c
中找到了它的可能副本(您的问题仅在几个小时前就涉及到了这一点)是否有任何方法可以从method1返回[u8]。@AlexanderSupertramp:否。[u8]
是动态调整大小的,这意味着编译器不知道为返回值分配多少堆栈空间。这通常通过间接方式解决。这就是Vec
内部正在做的事情。