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
Exactly. Since *something* has to own the inner node, you can't do non-trivial things to lists in a function. e.g. fn list(x: i32, y: i32) -> List<'static> { Cons(x, &Cons(y, &Nil)) } `&Nil` is actually fine since `Nil` is a constant value, but `&Cons(y` is invalid
1 reply 0 retweets 0 likes
Playground example for completeness. Only list2 fails to compile. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=08be5beb0e15553451f4decf0919c969 …
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.