Cannot borrow immutable borrowed content as mutable when implementing a binary tree with Rc

后端 未结 1 1673
傲寒
傲寒 2021-01-26 03:11

I want to implement a binary tree. My main language is C++ so the code is probably not idiomatic Rust, but compiling the following code:

use std::rc::Rc;

struct         


        
1条回答
  •  深忆病人
    2021-01-26 03:22

    Here's a MCVE of your problem:

    use std::rc::Rc;
    
    struct Node;
    
    impl Node {
        fn insert_left(&mut self) {}
    }
    
    fn main() {
        let root = Rc::new(Node);
        root.insert_left();
    }
    

    You can arrive at an example like this by removing as much code as possible while still getting the same error. This process helps tremendously to build understanding of the problem.

    The problem is that Rc disallows mutation of any kind. As stated in the documentation:

    Shared pointers in Rust disallow mutation by default, and Rc is no exception. If you need to mutate through an Rc, use Cell or RefCell.

    Therefore, there's no way to go from a Rc to a &mut Foo, which would be needed to call the insert_left method.

    As documented, you can use one of the types that allows interior mutability, such as a Cell or RefCell. These function a bit like a mutex, but are not valid for multithreaded scenarios. They ensure that only one mutable reference to a value is available at a time, a key component of Rust's safety.

    If you don't need the functionality of Rc's sharing, you can just move to having an Option> as well.

    0 讨论(0)
提交回复
热议问题