包含递归数据结构的 Box

递归数据类型或具有动态大小的数据类型需要使用 Box

#[derive(Debug)]
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}

fn main() {
    let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{list:?}");
}
StackHeaplistCons1Cons2Nil
  • If Box was not used and we attempted to embed a List directly into the List, the compiler would not compute a fixed size of the struct in memory (List would be of infinite size).

  • Box 大小与一般指针相同,并且只会指向堆中的下一个 List 元素, 因此可以解决这个问题。

  • Box 从 List 定义中移除后,画面上会显示编译器错误。如果您看到“Recursive with indirection”错误消息,这是在提示您使用 Box 或其他类型的引用,而不是直接储存值。