&‘a mut self is restrictive

Posted 金庆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了&‘a mut self is restrictive相关的知识,希望对你有一定的参考价值。

&'a mut self is restrictive

From https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#5-if-it-compiles-then-my-lifetime-annotations-are-correct

#[derive(Debug)]
struct NumRef<'a>(&'a i32);

impl<'a> NumRef<'a> {
    // my struct is generic over 'a so that means I need to annotate
    // my self parameters with 'a too, right? (answer: no, not right)
    fn some_method(&'a mut self) {}
}

fn main() {
    let mut num_ref = NumRef(&5);
    num_ref.some_method(); // mutably borrows num_ref for the rest of its lifetime
    num_ref.some_method(); // ❌
    println!("{:?}", num_ref); // ❌
}

If we have some struct generic over 'a we almost never want to write a method with a &'a mut self receiver. What we’re communicating to Rust is “this method will mutably borrow the struct for the entirety of the struct’s lifetime”. In practice this means Rust’s borrow checker will only allow at most one call to some_method before the struct becomes permanently mutably borrowed and thus unusable. The use-cases for this are extremely rare but the code above is very easy for confused beginners to write and it compiles. The fix is to not add unnecessary explicit lifetime annotations and let Rust’s lifetime elision rules handle it:

#[derive(Debug)]
struct NumRef<'a>(&'a i32);

impl<'a> NumRef<'a> {
    // no more 'a on mut self
    fn some_method(&mut self) {}

    // above line desugars to
    fn some_method_desugared<'b>(&'b mut self){}
}

fn main() {
    let mut num_ref = NumRef(&5);
    num_ref.some_method();
    num_ref.some_method(); // ✅
    println!("{:?}", num_ref); // ✅
}

以上是关于&‘a mut self is restrictive的主要内容,如果未能解决你的问题,请参考以下文章

为啥 &mut self 允许借用 struct 成员,但不允许将 self 借用到不可变方法?

如何实现对`async fn(&mut self)`进行轮询的`Future`?

is_null(self::$_instance) && self::$_instance = new self();

Java,AWTUtilities,eclipse报编译错误:Access restriction: The type 'AWTUtilities' is not API (restr

为啥在某些 trait 方法调用中会出现来自 &mut 的引用减弱?

别名可变原始指针 (*mut T) 会导致未定义的行为吗?