Borrow checker on parent-child relation

前端 未结 2 1568
南笙
南笙 2021-01-14 17:39

I have the code below producing the error message marked in its comments. I think I understand the message: I want to borrow parent two times: once for finding its child, a

2条回答
  •  长发绾君心
    2021-01-14 18:01

    and the mutable/immutable words in the error are not relevant

    I'm not sure why you think this. Mutability is very important in Rust! For example, while you are allowed multiple references to immutable data at the same time, you are only allowed to have a single reference to mutable data at a time.

    First, you need to fix the mutability of parent:

    let mut parent = // ...
    

    Then, you will get an error from the line:

    parent.child.use_parent(&mut parent);
    

    When you run this line, you are implicitly mutably borrowing parent and child. This is done so that you can call use_parent, which requires a &mut self.

    However, you are also trying to get a second mutable reference as the argument! This is a no-no, because if you were allowed to have multiple aliasing mutable references, the compiler wouldn't be able to track it and make sure that you don't break the memory-safety guarantees.

    Suppose I remove the line self.dummy+=1; so there is only 1 mutable alias - can I get this to work?

    Let's look at some variations of the function signature

    fn use_parent(&self, parent: &mut Parent)
    // cannot borrow `parent` as mutable because `parent.child` is also borrowed as immutable
    
    fn use_parent(&mut self, parent: &Parent)
    // cannot borrow `parent` as immutable because `parent.child` is also borrowed as mutable
    
    fn use_parent(&self, parent: &Parent)
    // OK
    

    As I mentioned earlier, if you have a mutable reference to something, you aren't allowed to have any other references to that same thing (mutable or not).

    Also, note that it doesn't matter what the body of the method is! Rust only checks the signature of a called function to verify if it's safe to borrow something.

    So how do you try to solve your problem? Ultimately, you are trying to do something that is very difficult for the compiler to prove safe. You want a graph of mutable links. I'd highly suggest reading the module documentation for Rc which has an example of exactly this parent-child relationship.

提交回复
热议问题