Why can't we use RefCell
for recursive data structures in Rust?
Invalid:
enum List {
Cons(i32, RefCell<List>),
Nil,
}
Valid:
enum List {
Cons(i32, Rc<List>), // or Box<List>
Nil,
}
Why can't we use RefCell
for recursive data structures in Rust?
Invalid:
enum List {
Cons(i32, RefCell<List>),
Nil,
}
Valid:
enum List {
Cons(i32, Rc<List>), // or Box<List>
Nil,
}
RefCell
contains the object inside, wrapping it, it's not a heap allocated value. That's why the compiler says "recursive without indirection": RefCell
is not an indirection.
Box
and Rc
, on the other hand, contain a reference to an object allocated somewhere else, and therefore are indirections.
Without an indirection, the List
enum ends up being infinite since every Cons
contains a full List
enum inside its RefCell
.
You can not do recursive data structures that contain themselves as values, only as pointers or references.