在Rust中,我遇到了以下错误:
<anon>:14:9: 14:17 error: `mystruct` does not live long enough
<anon>:14 mystruct.update();
^~~~~~~~
<anon>:10:5: 17:6 note: reference must be valid for the lifetime 'a as defined on the block at 10:4...
<anon>:10 {
<anon>:11 let initial = vec![Box::new(1), Box::new(2)];
<anon>:12 let mystruct = MyStruct { v : initial, p : &arg };
<anon>:13
<anon>:14 mystruct.update();
<anon>:15
...
<anon>:12:59: 17:6 note: ...but borrowed value is only valid for the block suffix following statement 1 at 12:58
<anon>:12 let mystruct = MyStruct { v : initial, p : &arg };
<anon>:13
<anon>:14 mystruct.update();
<anon>:15
<anon>:16 mystruct
<anon>:17 }
error: aborting due to previous error
for the following code:
struct MyStruct<'a>
{
v : Vec<Box<i32>>,
p : &'a i32
}
impl<'a> MyStruct<'a>
{
fn new(arg : &'a i32) -> MyStruct<'a>
{
let initial = vec![Box::new(1), Box::new(2)];
let mystruct = MyStruct { v : initial, p : &arg };
mystruct.update();
mystruct
}
fn update(&'a mut self)
{
self.p = &self.v.last().unwrap();
}
}
fn main() {
let x = 5;
let mut obj = MyStruct::new(&x);
}
我不明白为什么mystruct
没有足够的生命周期。如果我注释掉mystruct.update()
这一行,那么它就能正常工作。更重要的是,如果我注释掉update
函数的主体,代码仍然会失败。为什么调用一个借用可变self
的空函数会改变事情的发展?
我不明白错误所指的引用是哪一个。有人能解释一下吗?
'long: 'short
(意为'long
的生命周期比'short
更长)。因此,它应该写成fn update<'b>(&'b mut self) where 'a: 'b { ... }
。http://is.gd/EEKFnB - mdupself.p =&self.v.last()。unwrap();
这一行无法编译的问题。解释是,恰好在此行处获取的引用不会在update()
块之外存在,因此借用检查器正确地拒绝了它。http://is.gd/mlhHvbupdate()
中的代码行失败并不是因为引用的生命周期不超过块。它失败是因为该引用将指向结构本身,在 Rust 中这是不可能的。 - Vladimir Matveev'a: 'b
的符号表示法。这在哪里有文档记录?我也在参考资料中找不到它。 - loudandclear