为什么不能多次调用变异函数?

mic*_*srb 4 struct lifetime rust borrow-checker

这是基于我之前的问题

我的代码因借阅检查器错误而失败,因此我尽可能地减少了代码。结果如下:

struct MyStruct<'a> {
    s: &'a str,
}

impl<'a> MyStruct<'a> {
    fn foo(&'a mut self) {}
}

fn main() {
    let mut m = MyStruct { s: "aaa" };

    m.foo();
    m.foo();
}
Run Code Online (Sandbox Code Playgroud)

它失败了:

error[E0499]: cannot borrow `m` as mutable more than once at a time
  --> src/main-x.rs:13:5
   |
12 |     m.foo();
   |     - first mutable borrow occurs here
13 |     m.foo();
   |     ^
   |     |
   |     second mutable borrow occurs here
   |     first borrow later used here
Run Code Online (Sandbox Code Playgroud)

代码减少了太多,以至于它没有任何用处,例如可以通过删除函数的'a生存期来进行修复foo。但是我想理解为什么代码不能正常运行。

My understanding is that MyStruct contains reference to str of some lifetime 'a and foo can be called with self pointing to MyStruct of the same lifetime. I don't see why is m considered mutably borrowed after the first call to foo.

Den*_*ret 8

When you declare foo as

 fn foo(&'a mut self) {}
Run Code Online (Sandbox Code Playgroud)

you say the mutable borrow of self has the same lifetime 'a as the embedded string. So it stays borrowed as long as the struct lives. Calling foo is like definitely giving away the ownership of the struct.

You can fix it by declaring foo as

 fn foo(&mut self) {}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

76 次

最近记录:

6 年,8 月 前