给出的例子为
fn main() {
let v = 0u64;
let mut a = A {
x: "hello".to_string(),
y: &v,
};
a.hello();
a.world();
}
struct A<'a> {
x: String,
y: &'a u64,
}
impl<'a> A<'a> {
fn hello(&'a mut self) {
self.world();
self.x = "hello123".to_string();
let _ = *self.y;
self.world();
}
fn world(&mut self) {
self.x = "world".to_string();
}
}
构建它会产生错误
|
9 | a.hello();
| --------- first mutable borrow occurs here
10 | a.world();
| ^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
但是,更改签名A::hello
(即消除显式的'a
注释)到
fn hello(&mut self)
将修复该程序。
问题不在于显式生命周期,而在于使用same可变借用和其中数据的生命周期A
。
当我们写出被省略的生命周期时,没有显式注释的版本就变成了
impl<'a> A<'a> {
fn hello<'b>(&'b mut self) {
//…
}
}
通过强迫'a
and 'b
是相同的(在你的情况下通过重用'a
)你告诉编译器借用self
应与内部参考文献一样长A
并且由于所有引用都存储在A
必须比它活得更长久,至少直到A
超出范围。
这意味着一旦您致电您的hello
的实例A
在它的余生中被借用,因为该借用是排他性的,所以你不能在其他地方借用它。
这个问题对于world
函数,因为您不会强制其借用内部生命周期。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)