-
Notifications
You must be signed in to change notification settings - Fork 3.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
RefCell<Rc<?>> vs Rc<RefCell<?>> in Chapter 15.6 #1543
Comments
I am actually not 100% sure why we chose this way. @carols10cents do you remember? |
Any updates? That's an interesting point. |
Any update @steveklabnik @carols10cents ? |
I would say I feel better using Rc<RefCell>.
Most time, we need to do operations on the internal type T, the Rc, Weak and RefCell are just tools to allow us to do that. However, if we want to update a node in the tree, we will have to get a mutable reference, and I think it's the difference between having multiple owners of the data ( |
Elaborating on the link by @anurbol: The situations are quite different. In the book's example, we want to enable adding and removing children to a node in the tree. Putting
|
You're missing the option I'd suggest:
This option does allow you to add and remove children. The idea being that you always have a Rc<RefCell> and you can use |
That option only allows you to add and remove children if the Node isn't already wrapped in Good point though, I did miss that one. |
Confused by your last comment. Firstly, you say that you can't modify the Node if its been wrapped in an |
Sorry for the confusion. What I mean is that therefore you must use |
Hmm... no, if a node is in the tree it will be wrapped in Rc<RefCell<...>> which you can modify thanks to the RefCell. Rust playground link to demonstrate what I'm talking about: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3095de5c78afa4daeda9a82bd3a28f75 Basically, putting the whole Node in a RefCell is more or less equivalent to putting the individual fields in a RefCell, but I think slightly cleaner. |
Ah yeah. I see what you mean now. You're right, I didn't see how this approach could work before. |
I should have led off with a code sample :) |
Maybe, I think your explanation was good! I'm still very new to smart pointers. |
Another thought, I actually think your approach lends itself better to a refactor to support concurrency. Multiple owners of a lock makes more sense than a separately owned locks of the same piece of data. |
Chapter 15.6 of the Rust Book 2018 edition includes the following code:
This has a Rc inside a RefCell, but the pattern in other places and the previous section is put the RefCell inside the Rc. It would be nice if the book either used the more common idiom or explained why the rationale for not doing it.
The text was updated successfully, but these errors were encountered: