【发布时间】:2015-06-16 12:59:14
【问题描述】:
为什么会这样
#[derive(Debug)]
pub struct Foo<'a,'b> {
s : &'a str,
n : &'b i32
}
#[test]
fn test_struct() {
let f = Foo { s : &"bar" , n : &17 };
println!("{:?}",f);
}
但这不是
#[derive(Debug)]
pub enum Bar<'a,'b> {
Baz ( &'a str),
Fub ( &'b i32)
}
#[test]
fn test_struct() {
let b = Bar::Baz(&"Foo");
let c = Bar::Fub(&17);
println!("{:?} {:?}",b,c);
}
错误是(较大文件的一部分,因此忽略行号)
src\lib.rs:176:27: 176:29 error: borrowed value does not live long enough
src\lib.rs:176 let c = Bar::Fub(&17);
^~~~~~~~~~~~~~~~~~~~~~
在我看来,let c = Bar::Fub(&17),17 的生命周期与在堆栈上创建 "Foo" 的前一行的生命周期相同。如果我稍微修改一下并做
let h = &17;
let c = Bar::Fub(&h);
在这种情况下,很明显 h 的持续时间比 Bar::Fub() 长。所以我不确定如何才能让它发挥作用。
【问题讨论】:
-
"Foo"实际上并不存在于堆栈中,这与17不同。"Foo"是&'static str,所以它的寿命确实比17长。 -
我认为这是我正在寻找的实际答案