When to use Rc vs Box?

后端 未结 1 964
野的像风
野的像风 2020-12-14 18:54

I have the following code which uses both Rc and Box; what is the difference between those? Which one is better?

use std::rc::Rc;

         


        
相关标签:
1条回答
  • 2020-12-14 19:25

    Rc provides shared ownership so by default its contents can't be mutated, while Box provides exclusive ownership and thus mutation is allowed:

    use std::rc::Rc;
    
    fn main() {
        let mut a = Box::new(1);
        let mut b = Rc::new(1);
    
        *a = 2; // works
        *b = 2; // doesn't
    }
    

    In addition Rc cannot be sent between threads, because it doesn't implement Send.

    The bottom line is they are meant for different things: if you don't need shared access, use Box; otherwise, use Rc (or Arc for multi-threaded shared usage) and keep in mind you will be needing Cell or RefCell for internal mutability.

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