为什么在方法签名中添加`mut`会导致借用时间更长?

时间:2019-04-25 12:50:25

标签: rust semantics lifetime borrow-checker

请考虑以下程序。特殊之处在于,foofoo_mut的签名要求在生命周期self内借用'a,这也是T<'a>在类型{函数test1<'a>test2<'a>

test2可以正常编译,但是test1无法编译。为什么?它们是否具有相同的生命周期语义?我希望这两个功能都将被拒绝,因为t.foo()t.foo_mut()都应该借用t换来'a,因此直到test1和{{1 }}。

test2
struct T<'a>(&'a u32);

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

    fn bar_mut(&mut self) {}
}

fn test1<'a>(mut t: T<'a>) {
    t.foo_mut();
    // The following call is rejected because `t` is still borrowed.
    t.bar_mut();
}

fn test2<'a>(mut t: T<'a>) {
    t.foo();
    // The following call is allowed; it seems that `t` is not borrowed.
    t.bar_mut();
}

fn main() {}

Link to Rust Playground

0 个答案:

没有答案