Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Recursive types - confused on book paragraph
A value of a recursive type can have another value of the same type as part of itself. Recursive types pose an issue because Rust needs to know at compile time how much space a type takes up. However, the nesting of values of recursive types could theoretically continue infinitely, so Rust canโt know how much space the value needs. Because boxes have a known size, we can enable recursive types by inserting a box in the recursive type definition.
And the discussion hovers around:
enum List { // can't assign a size
Cons(i32, List),
Nil,
}
However, so can this structure suggested as solution:
enum List { // can't either, but it's on the heap.
// size it takes on stack _is_ defined now.
Cons(i32, Box<List>),
Nil,
}
My reading of it, is something like: Rust needs to know at compile time how much space anything that will be on the stack takes; which means Rust will only look up to the first Box
and then "disengage" (doesn't care whether it's recursive now.)
In other words, the problem with recursive types appears as long as it's supposed to be stack-allocated. So Box
fixes it.
Its size is still unknown.
Or is there something else I should be thinking instead?
6 posts - 3 participants
๐ท๏ธ rust_feed