rust 为什么显式生命周期注解会触发双重可变借用错误

e4yzc0pl  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(126)

给出的示例为

  1. fn main() {
  2. let v = 0u64;
  3. let mut a = A {
  4. x: "hello".to_string(),
  5. y: &v,
  6. };
  7. a.hello();
  8. a.world();
  9. }
  10. struct A<'a> {
  11. x: String,
  12. y: &'a u64,
  13. }
  14. impl<'a> A<'a> {
  15. fn hello(&'a mut self) {
  16. self.world();
  17. self.x = "hello123".to_string();
  18. let _ = *self.y;
  19. self.world();
  20. }
  21. fn world(&mut self) {
  22. self.x = "world".to_string();
  23. }
  24. }

字符串
生成它会产生错误,因为

  1. |
  2. 9 | a.hello();
  3. | --------- first mutable borrow occurs here
  4. 10 | a.world();
  5. | ^^^^^^^^^
  6. | |
  7. | second mutable borrow occurs here
  8. | first borrow later used here


然而,改变A::hello的签名(即消除显式的'a注解)

  1. fn hello(&mut self)


将修复程序。

huus2vyu

huus2vyu1#

问题不在于显式的生存期,它对可变借用和A内部的数据使用了相同的生存期。当我们写出被省略的生存期时,没有显式注解的版本变成

  1. impl<'a> A<'a> {
  2. fn hello<'b>(&'b mut self) {
  3. //…
  4. }
  5. }

字符串
通过强制'a'b相同(在本例中,通过重用'a),您告诉编译器self的借用应该持续与A内部的引用一样长的时间,并且由于存储在A内部的所有引用都必须比它更长,因此至少直到A超出范围。这意味着一旦调用了helloA的示例在其剩余的生命周期内都将被借用,因为该借用是独占的,您不能在其他任何地方借用它。
对于world函数,这个问题不存在,因为您没有在它的borrow上强制内部生存期。

相关问题