not sure I'm completely getting the necessity of Rc; per the book, this would not work: enum List { Cons(i32, &List), Nil, } fn main() { let x = Cons(3, &Nil); } because, the Nil would get dropped before you can take a ref to it
-
Show this thread
-
the solution is Rc: enum List { Cons(i32, Rc<List>), Nil, } fn main() { let x = Cons(3, Rc::new(Nil)); } why does this not cause the Nil to similarly be dropped? because Rc::new takes ownership of it?
2 replies 0 retweets 0 likesShow this thread -
it feels like a very ceremonious thing to do what normal refs *almost* do, so I'm not sure I've understood why it's needed
2 replies 0 retweets 0 likesShow this thread -
Replying to @mountain_ghosts
The book shouldn't be saying that doesn't work, it absolutely does. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f940a7d7f872fbff55dbfa8e7a2514f6 … The problem is it becomes a pain to work with. You only take references to nodes which means they have to be owned by something else. You can't construct a list in a loop for example
2 replies 0 retweets 0 likes -
Replying to @sgrif @mountain_ghosts
It's very similar to `&str` and `String`. `&str` is nice to pass around, but you often want an owned version instead (imagine if any struct that worked with strings had to be tied to the lifetime of an `&str`)
1 reply 0 retweets 0 likes -
Replying to @sgrif
I think that's the thing that hadn't clicked: having this: enum List<'a> { Cons(i32, &'a List), Nil, } it's not painful necessarily b/c the &'a List must outlive the outer List -- it's that something else needs to own the inner List
2 replies 0 retweets 1 like -
Replying to @mountain_ghosts @sgrif
i.e. things without owners get dropped, so you'd rather the list/tree/graph/whatever owned all its contents
2 replies 0 retweets 0 likes -
Replying to @mountain_ghosts
Yeah, a general rule of thumb is that structures want to own their contents, functions want to borrow them.
1 reply 0 retweets 0 likes -
Replying to @sgrif
so if a structure can contain multiple routes to the same thing (a graph), then I use Rc, got it :)
1 reply 0 retweets 0 likes
Or `Arc` if you want to be able to pass it across threads.
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.