知识卡片

普通读书笔记卡 · 6074.g.6 · 生成模型:未记录

递归布局需要间接层

理解等级:中级

enum List { Cons(i32, List), Nil } 的 Cons 要求在自身内放一个同样大小的 List,递归布局无法求解。改为 Cons(i32, Box<List>) 后直接保存的是已知大小的指针,后继 List 另处存放。Nil 决定具体值何时终止,间接层决定其类型布局能否成立。

相关卡片 [[Cons 表由配对构成]]、[[Box 提供独占堆存储]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 智能指针 Enabling Recursive Types with Boxes · 查看原书依据

      Because a Box<T> is a pointer, Rust always knows how much space a Box<T> needs: a pointer’s size doesn’t change based on the amount of data it’s pointing to. This means we can put a Box<T> inside the Cons variant instead of another List value directly. The Box<T> will point to the next List value that will be on the heap rather than inside the Cons variant.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第15章 智能指针(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c15.xhtml`,块 0064) - 结论依据:使用 Box 后只需给后继指针分配已知大小,消除内联布局的无限递归。 - 原始内容:Because a Box<T> is a pointer, Rust always knows how much space a Box<T> needs: a pointer’s size doesn’t change based on the amount of data it’s pointing to. This means we can put a Box<T> inside the Cons variant instead of another List value directly. The Box<T> will point to the next List value that will be on the heap rather than inside the Cons variant.