为什么这项工作
#[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()更长。因此,我不确定如何才能使它正常工作。
这是结构中枚举的生命周期参数的后续操作
对我来说,似乎让c = Bar :: Fub(&17),它的寿命与在堆栈上创建“ Foo”的前一行的寿命相同
字符串文字始终具有'static
生命周期,因此将始终存在足够长的时间。
我认为问题是您遇到的事实是枚举表达式实际上有点像函数调用。有点意思是在计算Enum的生存期时会忽略参数的生存期。枚举的生命周期显然要大一些,就像您写的那样:
let c: Bar;
let x = &17;
c = Bar::Fub(x);
在这种情况下,完全清楚的是,h的持续时间比Bar :: Fub()更长。
是的,这里的生命周期很清楚,并且可以在游戏围栏中使用:
let x = &17;
let c = Bar::Fub(x);
所以我不确定你在问什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句