Rust 核心:分发、单态化与胖指针 — Jon Gjengset
本页标题、字幕、摘要和阅读笔记为已保存的 AI 译文,可能有误。时间戳与来源一致,可展开查看原始字幕,并对照原视频核对。
Jon Gjengset 深入探讨 Rust 中的静态与动态分发,涵盖泛型、单态化、虚表、trait 对象、自动 trait 以及 Sized 约束。
文字稿来源:创作者上传至 YouTube 的字幕。AI 标点由 Vidleaf 添加;原始措辞和时间戳锚点均保留。原始文字稿见下方。
AI 生成的摘要
这段 Rust 直播涵盖了一组半相关的主题——trait、静态与动态分发、Sized trait、宽指针或胖指针、vtable 以及一致性——旨在解释它们如何相互配合,而不会在任何一个细节上陷得太深,为了控制时间可能会跳过一些细节,深入探讨可能会留到以后。它解构了 Rust Book 中关于泛型性能的部分,特别是单态化:通过在编译时填入具体类型,将泛型代码转换为特定代码,例如当一个泛型 strlen 接受任何实现了 AsRef<str> 的类型,并用一个 &'static str 和一个 String 调用时,编译器会生成两份副本;或者当一个泛型 HashMap 针对所使用的每种类型获得其结构体和方法副本,按需生成。这使得将 Rust 代码作为库发布(例如动态链接库)有些困难,因为需要源代码来为使用方的类型生成实例;好处包括通过内联和优化可能获得更高效的代码,而缺点包括二进制文件更大、指令缓存效率略差以及一些编译器开销。静态分发通过一个为 str 实现的自定义 trait 来解释,其中具体类型在编译时已知,因此调用变成对已知位置的汇编调用;动态分发是当不希望有多份副本时的替代方案,例如一个包含实现了该 trait 的各类元素的向量。演讲随后解释了为什么不能创建包含不同类型元素的向量、GUI 绘制示例、由 dyn 指示的 trait 对象、每个 trait 约束隐式要求的 Sized 标记 trait、类型擦除、持有数据指针和 vtable 指针的胖指针、对象安全规则,以及为什么像 Clone 和 Extend 这样的 trait 不能成为 trait 对象。后面的部分涵盖了动态大小类型、trait 对象和分发:一个 DIN trait 变成一个 pointy trait,其元数据是 DIN 元数据,一个指向 vtable 的指针,该 vtable 持有类型大小、对齐、drop 和 place 指针以及方法指针;pointy trait 同样可以为不带引用的 U8 切片实现,以 U 大小的长度作为元数据。该特性仍然很新且处于实验阶段,演讲者建议阅读 RFC,其中包含一个 trait 别名 thin,适用于任何实现了 pointy 且元数据为空的类型,提供了用于内省指针元数据的方法,并且关键的是允许在运行时动态构造 vtable,正如标准库已经为异步中的 waker 所做的那样。他对比了 fn、dyn fn 和 impl fn,指出对 U8 切片引用如何存储其长度存在不确定性,并解释只有结构体的最后一个字段可以具有动态大小类型。一位听众关于 dyn 的切片 Vec 的请求引出了 trait 对象、vtable 和 Any trait:数组元素必须被做成相同大小,并且不同的编译单元可能会为同一类型和 trait 生成不同的 vtable。Any 被描述为一个带有一个返回编译器唯一类型标识符的函数的 trait,被添加到 vtable 中以允许向下转型。本次会议在大约 2 小时 15 分钟时结束,并表示感谢。
根据文字稿生成。请对照原始视频核查所链接的段落。
带时间戳的章节摘要
特型、分发与单态化
流范围:特型与分发主题
- [0:28] 本流涵盖与特型、动态与静态分发、Sized 特型、宽指针或胖指针、虚表以及一致性相关的半关联主题块。
- [0:52] 这些主题相互关联,有些关联更紧密,目标是解释它们如何工作并相互配合,而不至于陷入任何一个细节过深。
- [1:13] 大多数主题将以可操作的细节覆盖,后续流中可能进行深入探讨,因此为控制时间可能会跳过一些细节。
Rust 书中关于泛型性能的章节
- [1:35] Rust 书有一章关于泛型类型、特型和生命周期,其中包括一小节关于使用泛型的代码性能。
- [1:59] 本流旨在解构该节表面的魔力,特别是单态化的概念。
- [2:07] 单态化被描述为通过填充编译时使用的具体类型,将泛型代码转换为特定代码的过程。
泛型 strlen 示例
- [3:17] 一个泛型函数 strlen 接受任何实现了 AsRef<str> 的类型,并通过 as_ref().len() 返回 usize。
- [3:46] 等价形式是一个对 S 泛型的函数,其中 S 实现了 AsRef<str>,两者都是接受任何可转换为 str 引用的类型的泛型函数。
- [4:36] 函数 foo 用 "hello world"(一个 &'static str)和 String::from("hello world")(一个 String)调用 strlen,显示两次调用传递了不同的类型。
- [5:30] String 实现了 AsRef<str>,因为对 String 的引用可以简单地产生对 str 的引用,因为 String 的内部表示就是 str。
泛型调用的单态化
Rust 泛型中的单态化
泛型类型的按需代码生成
- [6:54] 单态化不仅适用于函数,也适用于类型。
- [6:59] 泛型 HashMap 会为每个与之配合使用的类型完整复制该结构体及其所有方法。
- [7:13] 对于从未被调用的类型不会生成副本;生成是在编译期按需进行的,而不是为所有可能的类型都生成。
- [7:34] 只有当某个类型组合确实出现在代码中的某处时,才会生成该 HashMap 类型实例。
二进制分发与对源码的需求
- [7:46] 这也是编译 Rust 代码并发布可用作库的二进制文件(例如动态链接库)有些困难的原因之一。
- [8:11] Rust 的约定是为每个类型生成该函数的不同副本,但使用方可能用源函数所在位置未定义的类型来实例化它。
- [8:26] 因此需要源码来生成所有这些实例。
具体化代码带来的性能提升
- [8:31] 单态化非常出色,因为它可以生成潜在效率高得多的代码。
- [8:54] 对于 HashMap,每个具体的键类型都有自己的副本,因此编译器可以为每个键类型内联哈希函数。
- [9:26] 以字符串为键的 HashMap 版本将字符串哈希代码直接放入 HashMap 代码中,并可以基于类型为字符串这一事实进行优化。
- [9:41] 对于数字键,一旦泛型被单态化,编译器可能完全跳过哈希,不过讲者指出实际情况可能并非如此。
- [9:54] 编译器能够看到所用特定类型的具体展开代码,从而可以更好地进行优化。
更大的二进制文件与部分方法生成
- [10:28] 单态化的一个缺点是最终二进制文件会更大,因为会为每个配合使用的类型生成该类型或函数的副本。
- [10:45] 增长幅度并不像乘以类型数量那么严重,因为只会为给定类型组合实际调用的方法生成代码,这在一定程度上分摊了开销。
- [11:14] 单态化确实会导致最终二进制文件中包含更多代码。
指令缓存效率与编译成本
Rust 二进制文件大小、单态化与泛型
Rust 二进制文件较大的原因
泛型函数的单态化和内联
- [13:07] 单态化有帮助,因为像 bool_then 这样的泛型函数可以生成一个副本,直接内联传入闭包的代码。
- [14:18] 内联并非保证:因为函数被单态化为特定类型,编译器知道类型,如果愿意可以选择内联和优化。
标准库使用和代码重复成本
引用和动态链接的限制
Rust 中的静态分发和单态化
定义自定义 Hello trait
- [16:40] 演讲者定义了一个自定义 trait,称为 Hello 或挪威语问候,只有一个方法,不返回任何内容,只是用挪威语说你好。
- [17:10] 该 trait 为 str 实现,方法使用 self 打印一行。
具体 str 引用上的方法解析
- [17:46] 当为 str 引用上的调用生成代码时,编译器确定类型并检查该引用类型上可用的方法。
- [18:06] 它在引用类型上找不到名为 hi 的方法,然后查看作用域中的 trait,发现为接收者类型实现的 hi 方法,因此调用它。
泛型函数和单态化
- [18:21] 在采用实现了 hi 的类型的泛型版本中,编译器必须在不知道 H 类型的情况下调用该方法。
- [18:47] 单态化生成一个具体版本,例如 bar_str,其中 H 绑定到 str,因此具体类型是已知的。
编译时的静态分发
动态分发作为单态化的替代方案
静态分发与 impl Trait 语法糖
动机:避免多份副本
单一具体类型的切片
- [21:29] 如果所有元素都是同一类型,遍历向量并调用 `h.high` 是没问题的。
- [21:51] 一个接收实现了 High 的对象的切片的函数 `bar` 可以正常工作,并且在以单一具体类型调用时能顺利编译。
- [22:27] 将每个元素转换为字符串也没问题,不过讲者指出他们尚未为 string 实现这一点。
异构集合的需求
动态分发与 trait 对象
将不同的具体类型视为同一类型
- [24:00] 书中有一章相当不错,讲述了如何将不同具体类型的对象视为同一类型。
- [24:10] 一个 GUI 示例:许多对象都实现了 draw trait,例如按钮、图像和文本框,而 draw 函数只需要一个可绘制对象的迭代器。
- [24:39] 这类似于想要获取其中一部分东西,而这些部分可以调用像 high 这样的方法。
为什么单个泛型类型参数行不通
- [24:48] 这里需要的是所谓的 trait 对象,由 dyn 关键字表示。
- [25:05] 把 impl 简写展开后可以看出,Bar 对一个类型是泛型的,该类型必须是 str 引用或 String,不能两者兼有。
- [25:28] 对于切片或迭代器,没有地方放置第二个类型参数,因为迭代器的元素只有一种类型。
dyn 和未定长值引发的编译器错误
- [25:55] 写出裸 trait 类型会产生编译器错误,指出没有显式 dyn 的 trait 对象已被弃用,因此要加上 dyn。
- [26:16] 下一个错误说,类型 dyn high 的值的大小无法在编译时得知,并且 Sized trait 没有为 dyn high 实现。
- [26:29] 切片和数组的元素必须具有定长类型,讲者计划解释这个错误,以及 Sized 的含义和它如何与动态分发和 trait 对象相关联。
以类型擦除为预期目标
为什么 Rust 的 Sized Trait 对泛型类型很重要
Sized 作为带有隐式约束的标记 trait
- [27:54] Sized trait 没有方法,是定义在 marker 模块中的标记 trait,被描述为在编译时已知恒定大小的类型。
- [28:07] 大多数类型,包括像 Foo 这样的结构体和大多数标准库类型,都是定长的,只有极少数类型不是。
- [28:21] 每个 trait 约束,即使只是普通的 Foo<T>,都带有要求该类型为 Sized 的隐式约束。
编译器需要已知的参数大小来生成代码
- [29:05] 一个对实现 *str 的 S 泛型的 strlen,接收 S 并通过引用长度返回 usize。
- [29:34] 参数必须占用栈空间或通过寄存器传递,因此编译器必须知道它有多大,以便在生成的汇编中分配空间。
- [30:23] 对于 String 的实现,编译器知道参数是三个字(长度、分配大小和堆指针),因此可以轻松生成汇编。
- [31:02] 同样,对返回类型泛型也需要知道要为其分配多少栈空间。
为什么 dyn Trait 是未定长的,以及它为何会破坏切片
- [31:44] dyn Hi 表示任何实现了 Hi 的类型,但没有具体的值,因为切片中可能存放 String、str 或其他大小不同的实现者。
- [32:03] String 是两个数字加一个指针,str 是一个数字加一个指针,而假设的 Foo 可能有一个吉字节那么大,所以切片没有统一的元素大小。
- [32:28] 切片是连续的内存,其中每个块的大小都相同,因此如果元素大小未知,就无法保证元素大小相同。
- [32:52] 如果元素大小不同,就无法生成第四个元素的指针运算(起始地址加上元素大小的三倍),这就是切片和数组的元素必须具有定长类型的原因。
修复未定长集合的问题
Rust 的 Sized trait 与未定长类型
未定长参数导致的编译器错误
- [33:57] 编译该示例会产生错误:类型 din sRF str 的值的大小在编译时无法得知,并且 din as ref 未实现 Sized。
- [34:17] 编译器要求函数参数具有静态已知的大小,而借用类型的大小始终是已知的。
- [34:26] 编译器必须知道参数类型的大小才能生成函数调用代码,这使得定长类型成为一项基本要求。
Sized 的自动实现
- [34:59] 任何能够实现 Sized 的类型都会自动实现它,因此没有字段的结构体,或者持有 String 或 bool 的结构体,都是定长的。
- [35:27] 泛型结构体 foo<T> 仍然是定长的,因为每个 trait 约束都隐含了 T: Sized 的要求,所以所有字段都是定长的。
- [35:50] 你永远不会自己实现 Sized;它只作为自动 trait 使用。
编译器为何需要已知大小
- [36:09] 问题不在于栈大小,也不在于某个值是否可能放不进栈。
- [36:18] 在机器码或汇编层面,调用函数需要知道为其栈变量、参数和返回值分配多少空间。
- [36:49] 尽管有一些取巧的方法可以做到这一点,但编译器必须知道这些东西的大小才能生成高效的代码。
未定长类型的示例
- [37:19] 将裸 trait 用作参数类型(例如接收一个 high)不是 Sized 的,因为许多实现者可能具有不同的大小。
- [37:37] 在这里使用 impl 是泛型参数的简写,因此它是 Sized 的,因为通过静态分发和单态化,每个具体类型都会存在该函数的一份副本。
- [38:08] 直接接收 trait 本身(等价于写 din hi)行不通,因为它不是 Sized 的。
- [38:29] 持有 str 的结构体不是 Sized 的,因为字符串本身(而非指向它的指针)可以是任意大小;没有引用的切片同样不是 Sized 的,因为其元素数量未知。
- [39:01] 任何反过来包含这些非 Sized 类型的东西也不是 Sized 的。
解决 Sterling 2 单态化问题
为 Sterling 2 提出的非单态化方法
非 Sized trait 类型的间接化
通过指针使非 Sized 类型变为 Sized
- [39:58] 技巧在于通过一个对任意内部类型自身都是 Sized 的类型进行间接化,使该类型始终是 Sized 的。
- [40:17] 引用的大小始终相同,就是一个指针的大小,某些情况下是两个指针。
- [40:29] 编译器始终知道引用有多大,无论后面跟的是什么类型,因为它只是一个指针。
- [40:43] box 也只是指向堆的指针,因此一旦使用间接化,参数的大小就是已知的。
在不进行单态化的情况下使用 trait
- [40:54] 要在不进行单态化的情况下接收 trait 本身,需要把它放在某种指针类型之后,例如引用、box 或 arc。
- [41:28] Box 的定义使用了问号,意味着 T 不必是 Sized 的,从而跳过了“一切皆须 Sized”的自动约束。
- [41:50] 这就是为什么你可以创建一个本身不是 Sized 的东西的 box。
堆分配与具体类型
- [42:00] 当你最初创建 box 时,你进行了一次分配,其大小等于你将放入 box 中的内容的大小。
- [42:48] 创建 box 需要给它一个具体类型的东西,此时它会为该类型分配堆空间。
- [42:57] box 的大小仍然是已知的,因为它只是一个指针,即使它指向的东西可能具有任意大小。
- [43:13] 传递给函数的实际参数确实有大小,因此可以生成相关代码。
Box 与引用
Rust 中的 TraitObject 与类型擦除
TraitObject 的定义
- [46:17] 所构造的东西被称为 TraitObject,即一个唯一属性是表示某个 trait 的对象。
- [46:28] TraitObject 只表现为某个底层 trait,无论包装类型是什么。
- [46:44] Box 是一种指针类型。
转换回具体类型
- [46:49] 将 trait 对象转换回其原始具体类型通常是不可能的,尽管技术上有时可以通过 unsafe transmute 或 any trait 实现。
- [47:03] 将值转换为 trait 对象本质上是类型擦除:关于它曾经是什么类型的知识被擦除了。
- [47:26] unsafe 和 any-trait 魔法通常应被忽略。
只剩下 trait 的方法可用
动态分发与 vtable 机制
泛型调用的编译时代码生成
- [48:09] 当编译器为函数生成机器码时,它最终必须生成可以转换为可运行机器码的汇编代码。
- [49:29] 在泛型情况下,编译器会为每个具体类型获取一份代码副本,因此调用会变成直接跳转到二进制文件中已知的内存位置。
- [50:05] 对于具体实现,编译器在编译时就能静态地知道要跳转到哪里,因此代码生成变得非常简单。
trait 对象与未知的具体类型
- [48:51] 像 sayHi 这样的函数接收 Hi trait 的 trait 对象,而它实际上只是一个指针,因此编译器不知道 S 是什么类型。
- [50:14] 在动态情况下,编译器不知道值是 str 还是 String,因此无法决定要生成哪个地址。
虚分发表
- [50:29] 这种情况正是动态分发和 v 表(即虚分发表)发挥作用的地方。
trait 对象与动态大小类型
trait 对象指针中的额外类型信息
- [50:38] 构造 trait 对象意味着该引用或 box 的宽度不止一个指针;它携带了关于所指向类型的额外信息。
Rust 参考手册中关于动态大小类型的说明
- [51:24] Rust 参考手册指出,大多数类型具有编译时已知的固定大小,并实现了 Sized trait。
- [51:33] 大小仅在运行时才已知的类型称为动态大小类型,非正式地也称为无大小类型。
- [51:40] 切片和 trait 对象是动态大小类型的两个例子。
运行时类型确定示例
- [51:45] 大小仅在运行时才已知,因为在编译时无法确定将使用哪个具体类型。
- [51:58] 在一个示例中,从用户读取的值决定 say_hi 接收的是数字还是字符串,实际类型仅由不可预测的输入在运行时确定。
动态大小类型的指针大小
- [52:59] 指向动态大小类型的指针类型是有大小的,但其大小是指向有大小类型的指针的两倍。
Rust 中的 trait 对象与 v 表
trait 对象引用的结构
- [53:09] 指向 trait 对象的指针还会存储一个指向 V 表的指针。
- [53:23] 对诸如 dyn Hi 之类的 trait 对象的引用,会存储一个指向具体实现类型的指针,以及一个指向被引用 trait 的 V 表的指针。
V 表包含的内容
- [53:52] V 表,即虚分派表,是一种数据结构,保存着指向该类型每个 trait 方法的指针。
- [54:10] 对于 dyn Hi,V 表可以看作是一个 Hi V 表结构体,其中只有一个成员 hi,它是一个指向 Fn 的指针,该 Fn 接受一个指向任意 T 的指针。
- [54:47] 对于每个被转换为 trait 对象的具体类型,都会构造一个不同的 V 表。
在转换过程中构造 V 表
- [54:57] 将 str 转换为 dyn Hi 会得到一个指向 str 的指针,以及一个 Hi Vtable,其 hi 为 str as hi。
- [55:38] 在转换过程中,编译器构造 Vtable 并将其地址存储在引用内部。
- [55:59] 对于每个被转换为 TraitObject 的类型,都有一个这样的 Vtable。
生成的分派代码和按类型区分的 Vtable
Rust Vtable 与 trait 对象布局
Vtable 构造与胖指针
- [57:45] Vtable 是在编译时静态构建的,而不是动态分配的。
- [58:01] trait 对象是胖指针或宽指针,因为它包含两个指针,而不是一个。
- [58:16] 第二个指针通常是静态已知的,因为它由 trait 对象的原始构造决定,尽管从技术上讲,也可以动态地手动构造 vtable。
trait 对象中字符串切片的表示
Vtable 内容与调试
Vtable 标识与去重
- [1:00:12] 并非每次创建实例时都会构造新的 vtable;vtable 通常是针对类型静态构造的。
- [1:00:32] 相同的 vtable 不会去重,并且为两个不同类型实现的 trait 保证是不同的,即使它们包含相同的代码,因此它们具有不同的地址。
Trait 对象的 Box 与指针宽度
多 trait 的 trait 对象与 vtable 限制
为什么组合两个 trait 会失败
- [1:04:12] 要让组合了 Hi 和 AsRef 的 trait 对象工作,编译器需要知道 hi 方法和 asref 方法分别在哪里,但它们位于两个不同的 vtable 中。
- [1:04:29] 这将需要一个三宽指针而非两宽指针:一个指向数据的指针、一个指向 Hi 的 vtable 的指针,以及一个指向 AsRef 的 vtable 的指针。
- [1:04:44] 这种布局并非本质上不可能,但每增加一个 trait 都会使引用的大小不断增长,这很可能不是本意。
编译器生成的组合 vtable 与超 trait 变通方案
- [1:04:59] 理论上编译器可以为组合生成一个 vtable 并传入,但 Rust 编译器目前不这样做,演讲者也不知道有任何这样做的提案。
- [1:05:11] 一种变通方法是声明一个诸如 HiAsRef 的 trait,要求类型同时实现 Hi 和 AsRefStr 且自身没有方法,从而得到一个包含两个 trait 方法的单一更大的 vtable。
- [1:05:52] 这尚未在 Rust 本身中实现的部分原因是你可以自行选择启用,而不自动将加号变成更大的 vtable 向开发者表明这可能不是他们的本意。
多 trait 的编译器错误与建议
- [1:06:45] 编写 Hi + AsRefStr 会产生错误:只有 auto trait 才能作为 trait 对象中的附加 trait,因为 Hi 和 AsRefStr 都不是 auto trait。
- [1:07:14] 编译器建议创建一个新 trait,将所有这些作为 supertrait,并在此处改用该 trait,同时指出像 Send 和 Sync 这样的 auto trait 没有问题。
标记 trait 和无方法的附加 trait
Trait 对象与关联类型
关联类型导致 trait 对象编译失败
- [1:08:51] 向 trait high 添加一个名为 name 的关联类型,即使未使用,也会导致代码无法编译。
- [1:09:28] 编译器报告,在取 dyn high 的地方必须指定 trait high 中关联类型 name 的值。
- [1:09:39] 你不能接受任何 high 而不论其关联类型,因为该类型信息无法被捕获到 vtable 中。
指定关联类型以恢复编译
Trait 对象安全与让方法退出 vtable
为什么没有 self 的关联函数会破坏对象安全
- [1:11:20] 编译器报告该 trait 无法被转换为对象,意味着它不是对象安全的,不能成为 trait 对象。
- [1:11:34] 要使 trait 对象安全,它必须允许构建 vtable,以便调用可以被动态解析。
- [1:11:44] 错误具体指出该 trait 无法被转换为对象,因为关联函数 weird 没有 self 参数。
- [1:12:17] 无法调用 s.weird,因为 weird 不接受 self 或指针,也不存在可指向的有效实例。
- [1:12:36] 以 Hi::weird 方式调用它是有歧义的,因为没有任何东西指定使用哪个实现,即使存在默认实现也是如此。
- [1:13:14] 该方法不能出现在 vtable 中,因为没有 self,所以它与任何类型的任何实例都不关联。
使用 where Self: Sized 让方法退出 vtable
- [1:14:21] 给 weird 加上 where Self: Sized 约束后,要求实现该 trait 的类型必须是 Sized 的,而像 dyn Hi 这样的 trait 对象除非放在指针后面,否则不是 Sized 的。
- [1:14:43] 这实际上让该函数退出了 vtable,并且关键在于使它无法通过 trait 对象来调用。
- [1:15:06] 加上这个约束后,代码可以编译,并且仍然可以创建 trait 对象并调用 Hi。
- [1:15:30] 此时在 trait 对象上调用 weird 会失败,因为该方法带有 Sized 要求。
- [1:15:38] 这就是让某个特定函数不被纳入 vtable、从而使 trait 保持对象安全的方法。
禁止整个 trait 使用 trait 对象
- [1:15:50] 给整个 trait 加上 where Self: Sized 会完全禁止将该 trait 用作 trait 对象。
- [1:16:07] 这在实践中很少见;通常一个 trait 仅仅因为它的方法而不再是对象安全的。
- [1:16:22] 人们有时为了向后兼容会这样做,如果他们以后可能添加非对象安全的方法,就会提前加上这个约束。
关于关联类型与静态分发的观众提问
- [1:16:50] 演讲者询问关联类型的问题在静态分发下是否也会出现。
Rust trait 对象、静态分发与关联类型
静态分发与单态化
- [1:16:54] 在静态分发下,单态化意味着每个函数实现的具体类型都是已知的。
关于 trait 对象上假设的静态方法
- [1:17:06] 像 `s::weird` 这样的语法可能是可行的,其中 `weird` 被包含在 vtable 中,但调用时不带 self 参数。
- [1:17:41] 演讲者觉得这很奇怪:如果调用它本来就需要该类型的一个实例,那为什么不直接接收 self 呢?
- [1:17:53] 传统的例子是像 `new` 这样的方法,如果你已经有一个实例,就不需要调用它,所以它只会接收 self。
- [1:18:11] 演讲者同意类似这样的东西或许可行,但在实践中它通常并不太有用,这就是为什么它一直不是优先事项;可能还有更深层的原因,但演讲者不确定。
`where Self: Sized` 与具体的 DST
- [1:18:47] 对于一个带有 `where Self: Sized` 的 trait,演讲者认为你仍然可以为类似 `Box<dyn ...>` 的类型实现它。
- [1:19:11] 这样的 trait 不能再作为 trait 对象,但实现应该仍然是可能的。
- [1:19:24] 因为它是一个 box,所以需要双重引用,这没问题,因为 boxed 类型不是动态大小的;在指针后面包装使其具有大小,因此 trait 上的 `Self: Sized` 不会阻止这一点。
- [1:20:46] 如果问题指的是像 `str` 或 `u8` 这样的类型,那么不行,你不能这样做:当你有 `where Self: Sized` 时,Self 必须是有大小的。
vtable 中的类型擦除和关联类型
标准库中的 fromIterator 和 collect
fromIterator trait 和 collect
Rust FromIterator 和 Extend trait 机制
FromIterator trait 类型参数
- [1:21:38] 将迭代器收集到 Vec 能工作是因为 Vec 实现了 FromIterator。
- [1:21:49] FromIterator 的关联类型 A 是迭代器项的类型,因此结果是该项类型的 Vec。
- [1:22:00] trait 的泛型参数 T 是迭代器本身的类型,例如 HashMap 迭代器类型。
- [1:22:10] 一个 Vec<T> 可以从任何项为 T 的迭代器构造,无论具体迭代器类型是什么。
- [1:22:20] 演讲者指出该参数按理应命名为 I 表示 iter,但认为这不重要。
FromIterator 的 trait 对象问题
- [1:22:43] 使用 FromIterator 会给 trait 对象带来问题。
- [1:23:35] 一个接受 bool 的 FromIterator 并返回 Vec 的函数看起来应该没问题。
- [1:23:45] FromIterator 是个糟糕的例子,因为它不接收 self,所以无论如何都要求 self 是 Sized 的。
用 Extend 作为更好的例子
为什么 Extend 不是对象安全的
泛型 Extend 方法与单态化
- [1:25:05] Extend 对迭代器的条目类型是泛型的,而且尽管它接收 self,该方法对迭代器类型也是泛型的。
- [1:26:28] 由于单态化,编译器不会生成单个 extend 方法,而是生成多个副本,每个迭代器和条目类型的组合对应一个。
- [1:27:27] 不存在单一的 extend;每个迭代器和条目类型的组合都有一个。
所选实现缺少虚表条目
- [1:27:42] 条目类型 T 已经固定为 bool,但虚表仍然需要一个指向针对 bool 的特定迭代器类型的 extend 的指针。
- [1:28:05] 该迭代器类型没有在函数的类型中表达出来,而且按现有写法无法表达。
- [1:28:42] 当编译器尝试生成代码时,没有指向适当 extend 实现的指针,因此无法生成虚表。
无限虚表与无 trait 对象
- [1:28:52] dyn Extend 的虚表需要无限数量的条目,每个可能的 extend 实现对应一个。
- [1:29:04] 因此 dyn Extend 不可能存在,你无法为 Extend 创建 trait 对象。
为什么每次调用单态化的虚表会失败
对象安全与 Clone 特质
对象安全特质的要求
为什么 Clone 不能成为特质对象
- [1:31:38] 使用 dyn Clone 时,你只能做该特质允许的事情,而 Clone 只允许你进行克隆。
- [1:31:47] 编译器报告说特质 Clone 无法被做成对象。
- [1:31:58] Clone 有一个 fn clone,它接收 self 并返回 self。
未定尺寸返回类型问题
- [1:32:03] 对于 let x = v.clone(),x 的大小不明确,因为 dyn Clone 只是任意可克隆类型。
- [1:32:19] Clone 应该返回 self,而不是对 dyn Clone 的引用。
- [1:32:26] 由于具体类型被擦除,self 将是 dyn Clone,而它不是定尺寸的。
- [1:32:46] 函数的返回类型必须是定尺寸的才能生成代码,所以这无法工作。
- [1:32:51] 因此,如果特质要成为对象安全的,它就不能有返回 self 的方法,这就是为什么 Clone 不能被使用。
混合对象安全和非对象安全的方法
通过 where Self: Sized 实现 Iterator 特质对象安全
Iterator 的泛型方法与对象安全
- [1:33:23] Iterator 特质有关联类型 Item 和对象安全的方法 next,但也有泛型方法,如 chain、enumerate、by_ref 和 collect,其中 collect 依赖于 FromIterator 且不是对象安全的。
- [1:34:01] 迭代器仍然是对象安全的:在 dyn Iterator<Item = bool> 上,collect 不能在 trait 对象上调用,但 next 可以用可变接收者调用。
其中 Self: Sized 将方法从虚表中排除
- [1:35:03] 诸如 count 和 last 这样消耗 self 的方法带有 where Self: Sized 约束,泛型 chain 方法也是如此。
- [1:35:27] where Self: Sized 约束告诉编译器在将 trait 用作 trait 对象时忽略该函数,因此它不会被放入虚表。
- [1:35:44] 因此 trait 对象无法调用此类方法,但具体类型(如 Vec 的迭代器)可以,这使得 trait 可以保留一些锦上添花的方法,而不会让整个 trait 失去对象安全性。
关于允许的接收者类型的问题
- [1:36:13] 提问者询问接收者是否可以是任何包含 self 的类型,还是必须是 &self 或 &mut self。
Rust 对象安全规则与 trait 对象
超 trait 与关联常量
- [1:36:37] 所有超 trait 也必须对象安全,因为虚表是由所有超 trait 的并集构建的。
- [1:36:45] 要求 self: Sized 会使 trait 失去对象安全性,因为 Sized 不会成为超 trait。
- [1:36:52] 对象安全的 trait 不能有 associated constants,因为无处放置它们;将它们放入虚表会使虚表变得非常大,且其值不再全是函数指针。
可调度与不可调度函数
- [1:37:12] 所有关联函数必须要么可从 trait 对象调度,要么显式不可调度。
- [1:37:19] 可调度函数不能有类型参数(无泛型),且除接收者类型外不能使用具体的 self 类型,因此函数不能返回 self。
- [1:37:32] 接收者只能是 self 的引用、self 的可变引用、Box<Self>、Rc<Self>、Arc<Self> 或 Pin<&Self>——任何位于指针之后、能将未定长值转换为定长值的东西。
- [1:37:55] 这明确排除了 where Self: Sized 约束,从而允许 trait 即使某些方法不是对象安全的,整体仍保持对象安全。
关于添加 where Self: Sized 的建议
- [1:38:14] 库作者通常应考虑为非对象安全的方法添加 where Self: Sized,以防下游用户想要使用 trait 对象。
- [1:38:23] 这取决于该 trait 是否根本可用作 trait 对象;对于像 Clone 这样的 trait,添加该约束会让人们能创建 trait 对象但无法调用其主要功能,因此可能不值得。
- [1:38:48] 如果一个 trait 即使只能调用其对象安全的方法也有用,那么让其他方法选择退出、从而使整个 trait 对象安全可能是合理的。
Iterator::last 与 Sized 限制
- [1:39:14] Iterator::last 确实有 Sized 限制,只是被 rustdoc 隐藏了。
- [1:39:25] last 带有 where Self: Sized,因为它会消耗 self,而不是通过引用获取 self;Self 是一个未实现 Sized 的迭代器,而函数参数必须是 Sized 的,因此无法通过 trait 对象调用 last。
关于 trait 对象的一个秘密
- [1:39:55] 讲者指出,关于 trait 对象还有至少一件事尚未涉及:一个关于 trait 对象的小秘密。
Drop 与 trait 对象的虚表
Drop 作为对象安全的 trait
- [1:40:16] Drop 实际上是对象安全的,尽管一个只能被 drop 的对象似乎没什么意思。
- [1:40:26] 这在垃圾回收等场景中很有用,此时对象不会被立即 drop,而是存储在链表中并定期回收。
- [1:40:43] 将许多可能不同的东西存储在一个类型中需要 TraitObjects,因此 Crossbeam 将它们存储在 drops 中,技术上是在 drops 中装箱,效果相同。
通过虚表进行 Drop
- [1:40:59] 当 v 离开作用域时,会通过虚表调用 dropDrop。
- [1:41:34] 当装箱的 s 离开作用域时,存在一个堆分配,在函数返回时 s 被 drop 之前,可以通过 s.asref 使用它。
- [1:41:56] drop 一个装箱需要释放内存,但一个唯一方法是 asref 的 trait 对象仍然需要一种方式来做到这一点。
- [1:42:06] 每个虚表都包含 drop,因此任何 TraitObject 的虚表都包含指向具体类型 drop 函数的指针,这是必要的。
虚表中的大小和对齐
Rust 中的未定长类型与宽指针
trait 对象之外的未定长类型
- [1:43:04] 除了 trait 对象之外,其他类型也是未定长的,例如 [u8] 和 str。
- [1:43:20] 当 trait 对象放在引用或指针之后时,它会变成一个由数据指针和虚表指针组成的元组。
- [1:43:34] 指针后面的切片会变成一个宽指针,包含一个数据指针和一个存放切片长度的 usize。
- [1:43:50] 类似地,指针后面的 str 表示为数据指针加上一个 usize 长度。
无尺寸参数和返回值的编译器错误
- [1:43:57] 按值接收 [u8] 的函数会被拒绝,因为类型 [u8] 的值大小未知,而 [u8] 是任意长的 u8 列表。
- [1:44:21] 直接返回 [u8] 也会失败,因为函数的返回类型必须具有静态已知的大小。
用引用和 Box 掩盖无尺寸性
Rust 无尺寸类型与胖指针元数据
动态尺寸类型给编译器带来的挑战
- [1:46:04] 动态尺寸类型在编译器中有些特殊,因为编译器必须知道指针是否是宽的。
- [1:46:14] 自己处理无尺寸类型相当困难,不过为无尺寸类型实现类似 box 的东西是可能的。
- [1:46:27] 一旦涉及类型转换和允许 trait 对象,就会变得很麻烦。
RFC 2580 与 Pointy trait
- [1:46:33] 最近落地的一个 RFC,编号为 2580,增加了一个用于操作胖指针元数据的泛型 API。
- [1:46:48] 该 API 允许你指定胖指针第二部分类型。
- [1:46:58] DIN trait 会变成一个 pointy trait,其元数据是 DIN 元数据,即一个指向虚表的指针,该虚表保存类型大小、对齐、drop 和 place 指针以及方法指针。
- [1:47:28] pointy trait 也可以类似地为不带引用的 U8 切片实现,其元数据是 U 尺寸长度。
实验状态与 Thin trait 别名
- [1:47:44] 该特性仍然很新且处于实验阶段,演讲者建议阅读 RFC。
- [1:47:52] 该 RFC 包含一个 trait 别名 thin,用于任何实现了 pointy 且元数据为空的类型,即 thin 指针而非胖指针。
元数据内省与运行时虚表
原始 Waker 作为手动虚表示例
Rust 动态大小类型、切片以及 Box 与 Vec 对比
切片元数据和自定义动态大小类型
- [1:50:38] 演讲者不确定指向 u8 切片的引用是存储起始和结束指针还是长度,并指出两者基本等价。
- [1:51:01] 所引用的 RFC 弃用了 Nightly 中存在的 trait 对象和 raw parts 项的 thin 元数据,因为它是一个替代品。
- [1:51:29] 演讲者希望 RFC 能说明切片的关联元数据类型,但没有看到,并认为它就是长度。
- [1:51:46] 你可以某种程度上创建自己的动态大小类型:一个以 u8 切片作为最后一个字段的结构体会变成未定大小。
- [1:52:14] 只有结构体的最后一个字段可以具有动态大小类型,因为如果前面的类型具有任意大小,中间字段的偏移量就无法计算。
- [1:53:07] 如果未定大小的字段在最后,前面字段的偏移量是静态已知的,只需要最后一个字段的长度就能使类型定大小。
- [1:53:18] 指向这种结构体的引用通过存储指针和最后一个字段的长度来定大小。
Box<[u8]> 与 Vec<u8> 对比
Rust 中的 dyn fn、fn 与 impl fn
fn 作为普通函数指针
- [1:55:53] fn 参数必须是函数,不能是闭包,因为 fn 实际上只是一个保存地址的单一函数指针。
- [1:57:35] bar 需要一个实际的函数指针,因此不能传入闭包,因为没有地方存储捕获的数据。
dyn fn 作为宽指针 trait 对象
- [1:56:02] dinfn 是一个 trait 对象,其虚表保存用于调用函数的指针,它是一个宽指针,还包含数据指针。
- [1:57:10] foo 可以用捕获了 x 的闭包调用,因为调用时闭包需要通过宽指针的数据部分获得 x 的地址。
impl fn 作为泛型单态化
- [1:58:24] baz 可以用闭包调用,因为 implfn 是对任何实现 fn 的类型进行泛型化的语法糖,会为传入的每个闭包类型生成 baz 的具体副本。
- [1:58:40] 因为 baz 对每个单独的闭包进行单态化,捕获的数据可以轻松传入。
在 impl fn 与 dyn fn 之间选择
- [1:58:53] implfn 更通用,避免了通过指针间接调用,但它会为传入的每个闭包类型生成 baz 的副本,数量可能相当多。
- [1:59:12] 有时更倾向于使用 trait 对象而非泛型,否则泛型类型必须向上传播到调用者。
- [1:59:51] 如果包装结构体存储的是 box din fn 而不是对 f 泛型,包装结构体就不再是泛型的,因此调用者不必命名或传播泛型参数,这可以简化接口。
带 fn 参数的 trait 的对象安全性
一致性推迟;关于分发、虚表和 trait 检测的问答
将一致性推迟到单独的直播
回顾分发和 trait 对象概念
- [2:02:29] 演讲者询问静态分发和动态分发之间的一般区别、size trait、虚表、对象安全性以及宽指针和胖指针是否大致说得通。
- [2:02:45] 演讲者提出可以过一遍更多材料,以阐明这些为什么存在、它们的作用是什么以及它们的局限性是什么。
为什么通过虚表进行运行时 trait 检测不可行
dyn Fn 调用中的双重解引用
dyn Fn 的宽指针布局
- [2:05:23] 这个调用并不完全是双重解引用,因为参数是一个宽指针,而不是指向指针和虚表元组的指针。
- [2:05:33] 传入的是一个指向某个类型未知的 T 的指针,加上一个指向 T 的 Fn 虚表的指针。
解引用虚表以到达调用
动态分发、虚表技巧和泛型优化
比较虚表以进行向下转型
- [2:07:02] 对于实现 AsRef<str> 的类型 X,新的指针虚表动态元数据 RFC 可以允许将 s.vtable 与 string 的 AsRef<str> 实现的虚表进行比较。
- [2:07:41] 如果虚表匹配,可以将数据引用转换为字符串引用,并且对于可变引用,可以调用 push,尽管演讲者建议不要这样做。
- [2:08:07] 演讲者不确定编译器是否保证一个类型总是恰好有一个虚表。
泛型与动态分派优化
- [2:08:18] 编译器会进行相当多的优化,而装箱的 dyn fn 由于逃逸分析及类似技术,可能并不总是在堆上分配。
- [2:08:31] 使用泛型类型参数或 impl trait 通常能获得更好的优化,因为编译器在编译时能完全洞察相关类型,并基于具体实现进行协同优化。
- [2:08:52] 通过动态分派进行间接调用时,编译器会丢失一些原本可用于优化的信息。
请求的切片示例
- [2:09:07] 一位听众请求给出一个包含 dyn 的 Vec 切片的快速示例。
Rust trait 对象、虚表与 Any trait
使 dyn AsRef 数组与定长元素协同工作
- [2:09:15] 要使用类似 dyn AsRef<str> 作为 H 和 S,必须使数组元素大小相同,因为数组要求如此才能定位到给定索引。
- [2:09:56] 一旦元素大小相同,该方法即可正常工作,并且你还可以为内部类型使用 Box 或 Arc 等。
为何虚表在不同编译单元间可能不同
- [2:10:08] 不同的编译单元可能导致不同的虚表。
- [2:10:12] 据经验,Rust 可能使用多个独立线程编译一个 crate 的不同子集以加速编译。
- [2:10:25] 由于这些独立单元并发工作且同步较少,它们可能都会遇到用作 dyn AsRef 的字符串,并各自生成自己的虚表,而非协调一致。
- [2:10:40] 这可能导致即使对于相同类型和相同 trait 也产生多个虚表,这是该不变式可能不成立的一个例子。
Any trait 如何支持向下转型
- [2:10:57] Any trait 被描述为超级神奇,但它只是一个带有函数的 trait,该函数返回一个由编译器保证唯一的类型标识符。
- [2:11:19] 通过基于 Any 的 trait 对象,你可以对其使用类型 ID,因为它被添加到虚表中,从而获得该值的唯一类型标识符。
- [2:11:28] 该标识符让你能从 dyn Any 向下转型到具体类型,因为你知道类型标识符是什么。
- [2:11:46] Any 利用了大量先前讨论的机制,从 dyn trait(只要该 trait 包含 Any)转换为对实际底层类型的引用。
关于 Any 安全性的推荐阅读
直播收尾与未来的编程计划
本次会话的总结与时长
计划中的编程直播
结束致谢
- [2:12:44] 他感谢大家的到来,并表示下次再见。
前 3 段双语对照预览 · 免消耗额度
以下展示前 3 段已保存中文译文与英文原版字幕的逐段对照(零额度消耗):
大家好,欢迎回到又一期的 Crust of Rust。这一期,我希望我没有贪多,能在大概一个半小时到两个小时内讲完。我想等你们之后看这期录像时,就会知道我有没有成功了。那么这一期,我想讲的是……一组围绕 trait、动态分发与静态分发、size trait(比如宽指针或胖指针)的半相关话题。
Hello folks, welcome back to yet another Crust of Rust. This one, I'm hoping I didn't bite off too much to cover in like an hour and a half to two hours. I guess by the time you watch this recording afterwards, you'll see whether I succeeded or not. So for this one, what I wanted to cover was... a sort of chunk of semi-related topics around traits and dynamic and static dispatch, the size trait, like wide or fat pointers.
还有一些围绕虚表(V table)、一致性(coherence)之类的东西,它们都有这种动态与静态的取向。它们多多少少都相互关联,有些关联更紧密一些。而每一个我都收到很多问题。我想我应该专门做一期直播,把这些东西如何运作、如何相互配合都讲一遍。我希望我们不要……在任何一个细节上陷得太深。我想我会尽量以可用的详细程度把大部分内容都覆盖到。
And some of the things around like V tables, coherence, they all have this kind of dynamic and static approach to them. They're all sort of tied together, some more so than others. And I get a lot of questions about each one. And I figured I should just do one stream where we talk through how all of this stuff works and how it fits together. I'm hoping that we don't... end up too far down any one rat hole. I think what I'll try to do is cover most of it in sort of workable detail.
然后我们可能会在之后的某期直播里对其中的一个做深入探讨。但为了把时间控制住,你们可能会发现我跳过了一些细节,希望这没问题。那么这次我其实想从《Rust 程序设计语言》这本书开始。这本书有一章讲泛型类型、trait 和生命周期。其中有一个小节讲的是使用泛型的代码的性能。这一节,如果你读过这本书——如果你还没读过,我强烈推荐你读一读——可能会让你觉得,你读的时候可能会想,这听起来像魔法一样。
And then we might do sort of a deep dive on one of them in some later stream. But in order to try to contain it to the time, you might find that I skip over some of the detail, and hopefully that'll be OK. So I actually wanted to start this time on The Rust Book. So The Rust Book has a chapter on generic types and traits and lifetimes. And there's this one subsection in there on the performance of code using generics. And this is a section that, if you've read the book, and I highly recommend you do if you haven't already, might have struck you as, you might have read it and be like, that sounds like magic.
[0:07] 大家好,欢迎回到又一期的 Crust of Rust。这一期,我希望我没有贪多,能在大概一个半小时到两个小时内讲完。我想等你们之后看这期录像时,就会知道我有没有成功了。那么这一期,我想讲的是……一组围绕 trait、动态分发与静态分发、size trait(比如宽指针或胖指针)的半相关话题。
[0:44] 还有一些围绕虚表(V table)、一致性(coherence)之类的东西,它们都有这种动态与静态的取向。它们多多少少都相互关联,有些关联更紧密一些。而每一个我都收到很多问题。我想我应该专门做一期直播,把这些东西如何运作、如何相互配合都讲一遍。我希望我们不要……在任何一个细节上陷得太深。我想我会尽量以可用的详细程度把大部分内容都覆盖到。
[1:18] 然后我们可能会在之后的某期直播里对其中的一个做深入探讨。但为了把时间控制住,你们可能会发现我跳过了一些细节,希望这没问题。那么这次我其实想从《Rust 程序设计语言》这本书开始。这本书有一章讲泛型类型、trait 和生命周期。其中有一个小节讲的是使用泛型的代码的性能。这一节,如果你读过这本书——如果你还没读过,我强烈推荐你读一读——可能会让你觉得,你读的时候可能会想,这听起来像魔法一样。
[1:59] 在某种意义上,这个系列要做的就是拆解这种魔法,弄清楚里面到底是什么。特别是,它讲到了单态化这个概念。正如书中所说,单态化就是通过在编译时填入所使用的具体类型,把泛型代码变成具体代码的过程。但这有点抽象。所以我们先举一个稍微具体一点的例子,再由此展开。我们就用 new lib 吧。
[2:34] 我们把这个命名为。嗯,命名真难。其实无所谓,但正因为没有约束,反而更难。我们就叫它用挪威语写的示例吧。好,把这个测试删掉。
[3:06] 我们不需要测试。假设你有一个函数 greater。它在 T 上是泛型的。其实,我们弄得更简单一点。假设我们要有一个函数 strlen。它接收任何实现了 AsRef
[3:39] 非常简单的函数。我把它放大一点。所以这是一个泛型函数。你完全可以把它写成 s: S,返回 usize,其中 S 实现了 AsRef
[4:12] 所以这两个是等价的。它们并不完全一样,但做的是同一件事。而且它们都是泛型函数。它们可以接收任何能转换成 str 引用的类型,这正是这里所表达的,也正和这个 trait bound 的作用相同。接下来会发生的是,如果我们写任意一个函数,比如 foo,它调用 strlen,传入比如 hello world。然后它又调用 strlen,传入 String::from("hello world")。
[4:53] 用挪威语。这是挑选示例的一个很好用的捷径。所以,为了看清它们为什么不同,这里传入的是 &'static str 类型。这里传入的是 String 类型。哇,对吧?所以这就引出了关键点:这个函数是泛型的。它不只接受字符串引用。
[5:25] 它接受任何能转换成字符串引用的类型。比如 String 就实现了 AsRef
[6:08] 每种类型各一个。所以在编译时,我们最终得到的是类似一个 SterlingRefStir,它实际上接收一个 stir 并调用一个 stud Len。我们最终会得到一个 SterlingString,它接收一个字符串并做同样的事情。所以这个泛型定义会被编译器转换成这些多个非泛型实现。
[6:48] 这就是单态化的过程。这也是 Rust 中泛型工作方式的关键所在。这个过程不仅发生在函数上,也发生在类型上。所以想象你有一个对键和值泛型的哈希映射。你实际上会得到整个结构体及其所有方法的完整副本,每个使用它的类型各一份。注意,它不会为我们没有用其调用过的类型生成……副本。
[7:18] 这不像为所有可能的类型都生成。它是按需为任何类型生成,但按需是在编译时确定的。如果你看到代码需要这个函数用于某个给定类型,那么就在那个时间点生成它。类型也是一样。比如哈希映射,哈希映射类型的某个特定实例只有在那个类型组合实际出现在代码中时才会被生成。这实际上也是为什么让 Rust……编译 Rust 代码然后给人们发布一个可以作为库使用的二进制文件有点困难的原因之一。
[7:58] 因为想象一下,如果你在 Rust 库中有这个,而你想以二进制形式分发,比如动态链接库之类的,那实际上相当复杂,因为约定是 Rust 应该为每个类型生成这个函数的不同副本,但它可能在消费者中用一个未在源函数所在的原始库中定义的类型来实例化。因此,你需要源代码才能生成所有这些实例。
[8:31] 单态化之所以很棒,是因为你最终可能生成效率高得多的代码,对吧?Sterling 在这里是个不太好的例子,但让我们想象我们有一些稍微复杂一点的东西。实际上,一个很好的例子是 HashMap。我不会在这里写出 HashMap 的完整定义。但你最终得到 HashMap 是因为你为你使用的每个具体类型都得到该类型的一个副本。想象一下,HashMap 的一个实例的键是……
[9:06] 一个字符串,而另一个实例的键是数字,那么实际上最终编译器在为 HashMap 的每个方法生成代码时,它会生成——比如说,它会把每个键类型的哈希函数定义内联进去。所以,使用字符串的那个 HashMap 版本的代码,会把对字符串进行哈希的代码直接放进 HashMap 的代码里,并且它可以基于该类型是字符串这一事实来优化那段代码。
[9:40] 同样地,对于数字之类的东西,它可能能够完全跳过哈希,因为它意识到,一旦它对所有泛型进行了单态化,实际上哈希值就是数字的值。这可能并不完全正确,但你能体会到这种感觉:编译器能够看到所使用的特定类型的具体展开代码,这让它能够更好地优化。在我们进入这个更复杂的方面之前,这一切都说得通吗?泛型的一般概念以及为什么单态化很好,说得通吗?
[10:28] 所以缺点,正如聊天中有人观察到的那样,是的,对于单态化来说,缺点之一是你的二进制文件最终会更大,因为你需要为它使用的每一种类型生成该类型或函数的副本。它并没有像简单地乘以类型数量那么糟糕。原因之一是,例如对于 HashMap,你可能只对任何给定的类型组合使用一部分方法。它不会生成像……比如,如果你有一个以字符串为键类型的 HashMap,它不会生成整个 HashMap,也就是为字符串键类型生成 HashMap 的所有方法。
[11:08] 它只会生成你实际最终调用的方法。所以这稍微分摊了成本。但确实,它会导致最终二进制文件中有更多代码。而由此产生的一个副作用是,你的代码在某种意义上可能效率稍低,因为现在,不再是只有一个名为 Sterlin 的函数,也就是一段汇编、机器码序列,计算机可以跳转过去。
[11:40] 然后它可以把这些机器码行保留在缓存中,这样下次执行时就能更高效地运行。但最终你得到的是两个不同的函数,一些代码跳转到其中一个,另一些代码跳转到另一个,它们必须分别缓存,因为它们是不同的内存区域,所以实际上你的指令缓存效率会略微变差,这是一个缺点。从某种意义上说,这也有点昂贵,因为编译器确实需要生成这些副本,但通常这不算太大的开销,除非你用非常多的类型进行实例化。
[12:22] 嗯,这是 Rust 二进制文件比 C 二进制文件更大的主要原因之一吗?这略有不同。Rust 二进制文件静态编译了更多东西,这可能是部分原因。一部分是单态化。一部分是,我忘了具体细节,但我认为标准库中有更多东西被编译进去。另一个非常重要的原因是 Rust 经常内置调试符号。
[12:54] 如果你不从二进制文件中剥离它们,最终得到的二进制文件实际机器码很少,但调试符号很多,所以你可能想尝试直接剥离二进制文件。编译器会尝试内联生成的函数吗?是的,这就是单态化非常好的原因之一,因为它不仅内联 string 或 str,而且如果你有一个,比如说,PubFn,像……一个 bool then,它接受一个布尔值,还接受一个 f,它是一个函数,并返回一个 option t。
[13:42] 然后假设实现类似于,如果 b,则 some f,否则。这个函数实际上刚刚进入标准库,尽管是作为 bool 上的方法。所以在这里,如果你曾经用特定提供的……闭包或函数运行这个函数,它实际上会生成一个 bool then 的副本,并将你传入的闭包的代码直接内联到这个函数中。因此它可以相应地优化。
[14:14] 所以是的,它最终会内联。内联在这里用词不当。它可以选择内联并基于此进行优化。它不必这样做。只是因为它在特定类型上被单态化,它确切知道那个类型是什么,并且可以根据需要选择内联,这是一个重要的区别。体积更大的主要原因是标准库。
[14:44] 这并不完全正确,因为只有你实际使用的标准库部分才会被放进你的二进制文件中。不过,如果你大量使用标准库中的泛型,确实会导致体积增大。方法重复的成本有多大?基本上没有。我认为实际生成多个函数并不是那么重要,重要的是如果你生成了函数的许多副本,你就必须把每一个都编译成机器码,这会拖慢编译过程。strlen 字符串难道不应该接受引用字符串而不是按值传递字符串吗?
[15:23] 实际上两者都可以。它们都能工作,这也是接受引用字符串(askRefStir)的好处之一。动态库如何处理泛型?它们不处理。这就是为什么对 Rust 库进行动态链接,甚至只是以二进制形式分发 Rust 库都很困难的原因之一。而且我认为在 Swift 中,他们一直在尝试稳定类似的东西。
[15:54] 我们还不太清楚如何将其用于 Rust。而且,你不能把它用于类似这样的情况:如果你想要一个 C 动态库,比如一个在 Rust 中带有许多外部函数的动态链接库,那些函数不能是泛型的。好了。现在我们已经了解了单态化是什么,我想稍微谈谈这里实际的分派过程。
[16:27] 所以分派就是……实际上,让我给你一个稍微好一点的例子,我们可以在整个直播中多用一会儿。让我们定义自己的 trait。我们把这个 trait 叫做……就叫它 Hello 吧,足够简单了,或者我想我们用挪威语的“hi”。它只有一个方法。
[17:00] 假设它实际上不返回任何东西,它只有一个符号作为单个函数,让你用挪威语说你好。我们可以想象我们为比如 str 实现了这个 trait。嗯,它要做的就是打印一行,呃,self 哎呀。嗯,然后我们要做,呃,我想就用 J 点吧。
[17:40] 嗨。啊,今天打不了字。所以这里幕后发生的事情是,当编译器尝试为这段代码生成代码时,它确定这个的类型,然后查看仅在 str 引用类型上有哪些方法可用。它没有找到名为 hi 的方法。然后它查看作用域内的 trait,发现这个上有一个 hi 方法,它是为接收者类型实现的。
[18:18] 于是它最终调用了那个。看起来没问题。现在让我们设想我们有一个泛型版本,我们取某个实现了 high 的东西,我猜是 h。然后它就会调用 h.high。所以这个更棘手,对吧?当编译器必须为这段代码生成机器码时,它需要以某种方式调用这个方法,但它实际上并不知道 H 的类型。这就是单态化发挥作用的地方,对吧?
[18:51] 实际上,最终生成的是一个 bar str,它包含 H、B、str。现在,进行分派、确定这里该调用什么就变得很简单了,因为我们知道具体类型。这就是所谓的静态分派。也就是说,在编译时,编译器知道实际类型是什么。因此,当它尝试调用这个方法时,它就知道那就是这个方法。
[19:22] 它可以直接跳转到——基本上这会在汇编代码中变成一次调用,去调用这个函数,而该函数位于内存中某个已知位置,对吧?因为那就是这个方法所在的地方。静态分派讲得通吗?一旦你能生成这个方法,实际上弄清楚如何编译这段代码就变得很简单了,因为这个方法实际上和这个是一样的。而这两个都很容易确定 high 方法所在的位置。
[20:05] 现在我们已经看了这种静态分派,你可能会想,那替代方案是什么?如果我们不想为这个生成一堆不同的副本呢?这就是我们回到动态大小类型的地方。哦,抱歉,对,这里的 impl high 只是泛型的语法糖。这是等价的,就像我之前和 Sterling 展示的那样,这等价于 H 是 high。
[20:40] 这两个是等价的。对,那么替代方案是什么?我们不想要这种单态化,我们不想要多个副本。或者你可能会想到这个的另一个原因是,假设你想——假设你有一个实现了 high 的元素的向量。在 foo 这里,我想有一个这样的向量。
[21:21] 我想像这样 for h in 这个向量,调用 h.high。如果它们都是同一类型,那没问题。但如果我想要某种实现了 high 的元素的集合、序列或集合,但我不需要它们实际上是同一类型呢?我只关心它们实现了这个 trait。所以更具体地说,假设我想写 bar,我想接受任何是——比如说——实现了 high 的切片的东西。
[22:02] 让我们从这个版本开始,对吧。所以对于 s 中的 H,h 点 high。这运行正常。我可以用类似这样的东西调用 bar。运行正常,编译也正常。同样地,我可以把每个都转成字符串。那也运行正常。
[22:40] 哦,对了,我没有为字符串实现这个。所以那运行正常。但让我们想象一下,我希望能够用类似这样的东西调用它,这应该真的没问题。但我做不到,对吧?比如,我无法创建一个包含不同类型元素的向量。这本身就不是我能创建的东西。我真正想要的,但在这种情况下,我其实并不关心具体类型是什么。
[23:11] 我不关心它们是字符串。我只关心我希望它们实现 height trait 这一事实。这对我来说才是最重要的。所以我应该能够创建一个包含具有这种行为的东西的向量,而不关心具体类型。这就是我们进入动态分发和 trait 对象领域的地方。书中也有关于这一章的章节。让我找到它在哪。我打开的顺序错了,我真是傻了。
[23:50] 抱歉跳来跳去。它就在这里的章节下面。书中有一个相当不错的章节,讨论了将不同具体类型的东西视为同一类型的能力。他们使用的另一个例子是类似 GUI 的情况,你可能有很多可绘制的东西,比如它们实现了 draw trait。你可能能够接受,你可能想要一个 draw 函数,它只接受某种列表或迭代器。
[24:25] 所有要绘制的东西。其中一些可能是按钮,一些可能是图像,一些可能是文本框,但对 draw 函数来说并不重要。它只关心它得到一个可绘制东西的迭代器,这与此类似,对吧,我们只想接受一个可以调用 high 的东西的切片。你需要的是所谓的 trait 对象。trait 对象就是你看到 dyn 关键字的地方。
[24:58] 这实际上不会编译。所以我要做的是,这大概就是我想要的,对吧?所以,impl,记住,是简写,而这里实际写出类型会很有用,是这的简写。这多少给出了正在发生什么的线索。Bar 对一个类型泛型,该类型必须是 str 引用或 String。它不能同时是两者,因为它只对一个类型泛型。你可以想象我们这里有一个 H2 high,但考虑到我们接受一个切片或者假设一个迭代器,没有地方放 h2。
[25:38] 这里只有一个迭代器,它只包含一种类型的元素。所以这实际上行不通。在某种意义上,我们想表达的是,每个东西都是一个 high。它没有我们关心的其他具体类型。而事实上,如果我们这样写,就会得到一个编译器错误,说让我在新屏幕上调出这个。它说,没有显式 din 的 trait 对象已被弃用。
[26:10] 好,我们先消除这个警告。它说我们需要在这里放 din,所以我们就这么做。现在它说,类型 din high 的值的大小无法在编译时确定。所以它指向这里并说,在编译时没有确定的大小。trait sized 没有为 din high 实现。切片和数组元素必须具有确定大小的类型。这是你以前可能遇到过的错误。我们接下来在直播剩余部分要讨论的部分内容就是为什么会出现这个错误、它意味着什么、修复方法是什么、sized 是什么意思,以及它如何与动态分发和 trait 对象相关联。
[26:50] 让我在这里暂停一下,因为我刚刚向你抛出了一堆东西。我们看看这是否说得通。所以这是一堆关于深色模式和浅色模式的讨论。所以实际上,我们想表达的是,你可以把这看作是一种类型擦除。我们想说,我想取一个东西的集合,而我只关心它们实现了这个 trait 这一事实。
[27:26] 我有点想取这个 trait 的抽象概念。好,所以编译器指出的挑战是,在这种情况下,我们甚至要从哪里开始呢?好,我想我们需要先谈谈 sized。所以让我们转到 sized trait。sized trait 没有方法。它是一个标记 trait。
[27:58] 这就是标记模块中的内容。描述只是说,在编译时已知恒定大小的类型。现在,大多数类型都是 sized 的。比如如果你创建一个结构体 foo,它很可能是 sized 的。标准库中的大多数类型都是 sized 的。事实上,非 sized 的类型非常少。少到实际上,你拥有的每个 trait 约束,即使只是像 foo T 这样的,都有一个隐式约束,要求该类型是 sized 的。
[28:32] 要明白为什么,想想当……我们先把这注释掉一下。把这注释掉一下。我只想实际……我想我可以更聪明地做这件事。所以我们回到最开始那个非常简单的 strlen 例子,对吧?
[29:05] 它会对某个实现了 asterisk str 的 S 进行泛型化。它接收那个 S。并返回 uSize 作为引用长度。所以想象一下,有某个东西想要调用 strlen。嗯,strlen 接收一个参数,那个参数就是那个 s。所以它必须被传递一个东西。就像它需要以某种方式传递那个参数。嗯,它传递的参数必须在栈上占用空间,或者必须在寄存器中传递,二者之一。
[29:41] 这有点意味着编译器必须确保生成的汇编代码中有某种代码,为这个参数在栈上分配所需的空间。而这要求编译器知道参数有多大。如果这里的 s,我猜想想具体的实现,所以是 strlen str。这里,这只是一个,嗯。
[30:20] 让我们采用字符串实现。所以 string 实际上只是一个,它有点像是两个数字和一个指针,对吧?它是字符串的长度,它是分配的大小,以及它是指向堆上实际字符串中第一个字符的指针。所以它的大小。编译器知道这个参数的大小是三个字,三个。如果你愿意的话,是 use 大小,对吧。
[30:52] 因此我们可以轻松地为这个函数以及调用这个函数生成汇编代码,因为它知道参数占用了多少空间。你可以想象类似的情况,对吧,如果我们对返回类型进行泛型化,它就需要知道在栈上为返回类型实际分配多少空间。所以即使我们没有特别说明这里的 s 是有大小的,它基本上始终是一个要求,即类型是有大小的。因为如果不是这样,编译器就不知道如何为它生成所需的代码。对吧。
[31:35] 好的。那么为什么。为什么当我们尝试使用这个时它却能编译呢?嗯,dyn high 实际上只是说任何实现了 high 的东西,就像只是生成 high 而不给出具体值的东西。因为记住,我们希望这是一个切片,可能包含 string 和 str 以及任何其他可能实现这个 trait 的类型。而那些类型的大小都不同,对吧?string 是两个数字加一个指针,str 是一个数字加一个指针,你可以想象我们有一个类型 foo,它作为一个结构体有一个千兆字节那么大,或者类似疯狂的东西,对吧?
[32:16] 然后我们为它实现 hi,这也是我们可能想在这里传入的东西。所以这个切片没有大小。它并不是,就像如果你,切片实际上只是一段连续的内存,对吧?其中每个块的大小都相同。它是一个数组,其中所有元素的大小都相同。但如果我们不知道它们的大小,我们就无法保证它们的大小相同。如果我告诉你,如果我给你其中一个,那么这里的 din high 就没有大小,对吧?
[32:47] 因为它可以是任何类型,而 once high 可以是任何大小。然后我问你,给我第四个元素。通常在数组中,因为所有元素的大小都相同,第四个元素就是指向起始位置的指针加上大约三个元素的大小,对吧?这是指针运算,用来获取第四个元素。但如果它们的大小不同,你就无法生成那段代码。这就是为什么它说切片和数组元素必须具有大小类型,因为否则这个类型就说不通了。
[33:23] 那么我们怎么解决这个问题呢?我们真的很想能够做到这一点。如果 Rust 不让你把实现了某个 trait 的东西当作集合来讨论,那就太离谱了。而且数组并不是这里唯一的问题,对吧?即使我们取了,即使我们写了,这方面有什么好例子?假设我们这里有一个 strlen2,它接受一个类似 din asref str 的东西。它有同样的问题,对吧?
[33:57] 如果我尝试编译这个,你会看到它说了同样的话。让我把另一条消息去掉。它说,类型 din sRF str 的值的尺寸在编译时无法得知。Sized 没有为 din as ref 实现。函数参数必须具有静态已知的大小。借用类型总是具有已知的大小。然后它试图给你一个如何修复它的建议。但这又算是关键洞察,即编译器需要知道参数类型有多大。
[34:31] 否则,它就无法生成函数调用代码。所以这算是编译器的一个基本要求,即这些类型是有大小的。到目前为止这说得通吗,比如为什么这是个问题?你能给我们展示一下实现 sized 吗?所以 sized 会自动为任何能够实现它的类型实现。
[35:04] 所以如果你像 struct foo 这样没有字段,它是有大小的。如果你在那里加一个 string,string 是有大小的,所以 foo 是有大小的。如果你再加一个 bool,这个类型现在仍然是有大小的。类型只要能够有大小,就总是有大小的。例外情况会是,如果我做了类似……而事实上,即使我做了 foo t 而不是这个持有一个 t,它仍然是有大小的,因为记住每个 trait 约束都有一个隐式要求,即它是有大小的。
[35:38] 所以这里隐含地有一个 Sized 约束。这意味着 T 是 Sized 的。所以所有字段都是 Sized 的。因此对于任意 T,foo
[36:12] 问题不在于它可能放不下栈。问题在于,为了调用一个函数——就在机器码层面,或者把它想象成汇编层面——为了调用一个函数,你需要在调用该函数时知道为该函数的栈变量分配多少空间。我们可能会包含它的一些参数,或者在调用方一侧。当你必须为返回值分配空间时,那个空间应该有多大?从根本上说,这只需要你知道空间有多大,因为你无法为创建那个栈生成机器码。
[36:49] 有一些取巧的办法可以做到这一点,但基本上,编译器为了生成高效的代码,必须知道这些东西的大小。让我们看看。哪些东西不是 Sized 的?我们已经讨论过 trait。所以如果我写 pub fn foo,并且我只是说我接受一个 impl。
[37:27] 这里的 impl 是一个 trait,很多东西都实现了该 trait,它们的大小可能都不同。所以它没有确定的大小。如果我在这里写 impl,impl 是 impl Trait 的简写。所以这个 impl Trait 是 Sized 的,因为对于每个具体类型,我们都会得到一份 foo 的副本。而对于每一份副本,类型的大小都是已知的。所以如果我们在这里使用静态分发进行单态化,这是没问题的。
[37:59] 但如果我们只是尝试接受 trait 本身,基本上就是说这个函数接受任何实现了该 trait 的东西,这就不行了,因为它不是 Sized 的。这等价于写 dyn Trait。这样就不是 Sized 的。我们稍后会讨论如何让这样的东西变成 Sized。嗯,另一个例子是类似这样的,嗯,如果我们回到我的 struct Foo,嗯,如果你试图让它持有一个 str,嗯,str 不是 Sized 的,嗯,因为字符串可以是任意大小——如果你想的不是指向字符串的指针,而是字符串本身,它可以是任意大小,嗯,同样地,嗯,这个,就像没有引用的切片,也不是 Sized 的,因为你不知道有多少个元素。
[38:51] 所以它没有明确定义的大小。这些是我所知道的关于非 Sized 事物的两个最好的例子。然后任何反过来包含这些类型的东西也是如此。聊天中有很多讨论试图解释我即将解释的内容——我们如何修复这个问题,以及为什么你需要引用之类的东西。我保证我会讲到的。
[39:28] 很好。所以我认为我们目前大致进展到的位置是合理的,看起来是这样。那么现在的问题就变成了,我们如何解决这个情况?我们希望能够拿一个,对于我们的 Sterling 2 来说,我们叫它 Sterling Din 吧。我们希望能够有一个像这样的方法,它不会被单态化。但这个不是 Sized 的,那我们该怎么办?这里的技巧是让它成为一个始终是 Sized 的类型。
[40:05] 而我们做到这一点的方式是通过某种本身对任何内部类型都是 Sized 的类型来进行间接引用。一个例子就是引用。所以引用的大小始终是一样的,它就是一个指针的大小,或者在某些情况下是两个指针,我们稍后会讲到。这个确实有大小。编译器始终知道其中一个有多大,无论后面跟着的是什么类型。因为这只是一个指针。
[40:40] 如果你有一个 box 也是一样的,对吧?box 也只是一个指向堆的指针。所以一旦我们这样做了,这个参数的大小现在就是已知的,我们就没问题了。而这实际上就是你在不进行单态化的情况下拿取某个东西、拿取 trait 本身的方式,就是把它放在某种指针类型后面。比如引用、比如 box、比如 arc。
[41:13] 在实践中它的工作方式是,如果你看 box 的定义,它里面有魔法,对吧?它不是魔法,但它里面有一堆东西。基本上,它只是一个指针。这不完全准确,但足够接近了。box 实际上有这个定义。而这里的问号意味着不必是。所以它基本上是在选择退出那个自动添加的、所有东西都必须是 Sized 的约束,说对于 box 来说,T 不必是 Sized 的。
[41:50] 这就是为什么你可以创建一个本身不是 Sized 的东西的 box。而它能工作的原因是,当你最初创建这个 box 时,你进行了一次分配,大小等于你将要放进 box 里的任何东西的大小。所以让我在这里写一个 main 来示例这一点。在某个时刻,我必须做 box new,比如 string from hello。
[42:25] 对吧?然后我可以说现在这将是一个 din as ref str。这里应该写 x。这里应该写 str。然后我可以用 y 调用 strlen din。所以在我创建 box 的某个时刻,我必须给它一个具有具体类型的东西。而在那个时刻,它在堆上为那个类型分配了空间。
[42:57] 但这个盒子的大小仍然是已知的,因为它只是一个指针。当我把它变成这里的盒子时,它在概念上仍然只是一个指针,即使它指向的东西可能具有任意大小。但我们传给这个函数的实际参数确实有大小,因此我们可以生成相关的代码。通过这样的类型进行间接访问,而间接类型的大小是已知的,这说得通吗?这能理解吗?
[43:37] 我们也会讨论 trait 的组合。让我想想。我保证我们会讲到多个 trait。你不能直接把 BoxedInAsteroidStir 放在 X 上吗?对,所以你也可以这样做。AsteroidStir。那也没问题。但即便如此,你仍然必须给 Box New 提供一个大小已知的具体类型。
[44:16] 什么时候应该用 box 而不是引用?比如什么时候选这个而不是那个?这没有硬性规定。一般来说,box 的优点是它是静态的。所以即使调用者的栈帧消失了,你仍然可以继续使用它。所以这跟平时什么时候选 box 而不是引用是一样的。那我也可以给函数一个指向栈的引用吗?对,完全正确。
[44:47] 所以你还可以这样做,让我在下面这里写。所以我完全可以这样做,然后 Sterlendyn,为什么?对。所以这个,假设我有一个 din2 接收这个,而这个可以调用 din2。
[45:25] 为什么这里报错?因为 box 也有一个星号方法。这就是为什么需要双星号。对,你看,我也可以对栈上的东西做同样的事。我可以创建一个类似通过指针间接访问的东西,然后把它传给一个接收引用的函数。
[45:59] 事实上,我觉得我甚至可以这样做。对,那没问题。为什么那个不行并不太重要。所以我们刚刚构造的东西叫做 TraitObject。它是一个只具有表示某个 trait 这一属性的对象。这就是 TraitObject 的含义。它们就是只作为某种底层 trait 行为的东西。
[46:35] 这是一个 TraitObject,这也是一个 TraitObject。外层包装类型是什么并不重要。Box 算是一种指针类型。对,box 是指针类型。我能把 trait object 转换回它原本的具体类型吗?我倾向于说不能,但严格来说有时可以。但一般来说,不能。你可以把它理解为,这本质上就是类型擦除。
[47:08] 从技术上讲,你可以通过不安全的 transmute 之类的方式回溯,但一般来说,一旦你把它变成 trait 对象,你就抹除了关于它原本是什么类型的知识。不过,围绕 unsafe 有一些魔法,围绕 any trait 也有一些魔法可以使用。但一般来说,你应该忽略这些。另外请注意,当你这样做时,你只保留了使用这个 trait 的能力。你抹除了关于具体类型是什么的所有其他知识。
[47:39] 所以对于一个装箱的 ASRF trait 对象,你唯一能做的就是调用 ASRF,别的什么也做不了。这里也是一样。我们稍后会深入探讨原因。好。那么这引出了一个有趣的问题。让我们举个例子,把这个设为二,把这个设为一,然后交换它们的位置,这样仍然能编译。现在让我们思考一下,当编译器必须为这个函数生成机器码时,实际会发生什么。
[48:15] 在某个时刻,它必须实际进行编译并生成汇编代码,这些代码随后可以被转换为可运行的机器码。所以这里的 S 是某个实现了 Sref 的类型。事实上,让我们回到我们的 Hi trait。那样会更好一些。所以让我们回到这里,假设我想要一个 sayHi,它接收一个 dinHi,不返回任何东西,只是调用 Hi。对吧?所以这将会是,这接收一个 Hi trait 的 trait 对象。但当编译器在这里生成代码时,它不知道 s 是什么类型。对吧?
[49:01] 它只是一个 trait 对象。它实际上只是一个指针。那么它如何调用 hi 方法呢?记住,在泛型情况下,是静态的 H。在这种情况下,我们实际上为每个具体类型都得到这个的一个副本。
[49:37] 所以实际上,这变成了这样。而对于这个具体实现,生成机器码是微不足道的,因为这实际上就像是一个汇编调用,调用到无论是什么,调用到这一行,调用到第 6 行。实际上不是行,而是二进制中的内存位置,但你明白意思,对吧?编译器在编译时静态地知道要跳转到哪里。
[50:10] 然而,对于动态情况,我们调用什么呢?我们不知道这是 str 还是 string,对吧?所以我们不知道应该生成这个的地址、这个的地址,还是完全其他东西的地址。那么这会变成什么机器码呢?好吧,这就是我们要进入动态分发和 V 表或虚函数分发表的地方。所以构造 trait 对象的诀窍在于,引用或装箱实际上只有一个指针宽这件事并不完全正确。
[50:48] 它实际上携带了一些关于所指向类型的额外信息。所以这里,让我们回到,回到 Rust 圣经。Rust 圣经有一章讲动态大小类型和 size trait。这在高级类型章节下。它讲的是,事实上,它甚至没有讲到我们想讲的那么多。这里。
[51:22] 让我们改用 Rust 参考手册。Rust 参考手册关于动态大小类型说,大多数类型有一个固定大小,在编译时已知,并实现 sized trait,就像我们讨论过的。大小仅在运行时已知的类型称为动态大小类型,或非正式地称为无大小类型。切片和 trait 对象是动态大小类型的两个例子。为什么这仅在运行时已知,因为在编译时,我们不知道这将会是什么类型。只有在运行时我们才会知道。
[51:54] 为了更具体一点,想象我有一个 main 函数,如果 rand,我没有随机数,random 是四。如果 random 是四,那么对这个调用 say hi,否则对来自 world 的字符串调用 say hi。对吧?
[52:30] 让我们想象 random 比 4 更随机。你在运行时之前不知道。假设这是从用户读取的。在编译时,你不知道这里将使用哪个实际类型。它仅在运行时由某些在编译时无法预测的输入决定。对吧?所以这就是为什么这在运行时确定。它说,指向动态大小类型的指针类型是有大小的,但大小是指向有大小类型的指针的两倍。
[53:09] 所以指向 trait 对象的指针也存储一个指向 V table 的指针。这就是我们进入什么是 V table 的地方。嗯,当你有一个 trait 对象时,比如 at din pi 这样的东西,引用中实际存储的是一,一个指向实际具体实现类型的指针,二,一个指向被引用 trait 的 V table 的指针。
[53:48] 那么什么是 V table?V table 或虚拟分发表是一个小数据结构,它有为该类型的 trait 的每个方法的指针。所以在 high trait 的具体情况下,假设我们有一个 din high,V table 将是一个你可以把它看作一个 high V table 结构体,它只有一个成员,即 high,它是一个指向 Fn 的指针,一个 Fn 实际上,它本身接受一个指向任何 T 的指针。
[54:45] 所以基本上,每个被转换成 trait 对象的具体类型最终都会构造出一个不同的 V table。所以当我们开始时,假设我们有一个 str,我们想把它转成一个 dyn High,实际构造出来的是——假设我们有一个——嗯,第一项变成一个指向 str 的指针。
[55:16] 第二项变成一个 High Vtable,其中 High 是 str as High,以及一个指向它的指针。当你进行这个转换时,编译器知道它必须构造这个 Vtable,并且它把那个 Vtable 的地址塞进那个引用里面。
[55:48] 所以这个引用包含两样东西:指向实际类型的指针,以及指向编译器在这个特定转换过程中生成的 Vtable 的指针。所以每个被转换成 TraitObject 的类型都会有一个这样的 Vtable。所以现在当编译器尝试生成这段代码时,它实际生成的是类似 s.VTable.High s.Pointer 的东西。
[56:23] 所以如果有人传入的是,比如说,一个 String,它就会有一个不同的 Vtable。所以 s.Vtable 会是一个不同的指针。所以在这种情况下,这会是 where is str High?比如第 6 行,对吧?所以这会是一个指向第 6 行的指针。但如果我们改成——我马上停下来回答问题。如果这改成从一个 String 转成 dyn High,它就会是一个指向 String 的指针和 String as High,也就是上面第 12 行上的这个方法。
[57:06] 换句话说,生成的这段代码无论传入哪个类型都能工作,因为我们通过 V table 进行间接访问,而每个类型都有自己独立的 V table。好,一下子扔给你们这么多内容确实有点多,但希望还不算太糟。我们看看。
[57:45] V table 本身是在编译时静态构建的,还是也是动态分配的?V table 是……V table 是在编译时构建的,它们是静态构建的。所以一般来说,第二部分……所以这就是所谓的胖指针或宽指针,因为它里面有两个指针,而不只是一个。所以每当你看到这个,它实际上就是一个宽指针。而且一般来说,里面的第二个指针总是静态已知的,因为它是由最初的构造决定的。
[58:23] 由 trait 对象决定的。我说“一般来说”是因为从技术上讲你可以在运行时动态构造它。这里的调用中没有任何东西要求它必须是静态已知的。所以你可以想象手动构造一个 vtable。这确实有被用到,我们稍后实际上会稍微讨论一下。Refster 还包含字符串切片的长度。
[58:56] 是的。所以一般来说,实际上会是这样。所以它不是指向实际字符串的指针。它实际上是指向 str 引用的指针,而 str 引用本身保存着长度。我们能不能以某种方式调试打印 Vtable 结构体?我不知道有什么办法能让编译器打印它的 Vtable 结构体,但它基本上就是这个。
[59:33] 它只是,对于这个 trait 对象所对应的 trait 的每个方法都有一个成员,其中每个成员是……每个成员是对应的方法,而值是指向该具体类型该方法实现的指针。那么,为什么不接受 self 的 trait 函数不是对象安全的?编译器难道不能直接生成一个不使用 self 的 fn mute self 吗?
[1:00:08] 我们稍后会讨论这个。每次创建实例时都会构造一个新的 V table 吗?不,V table 通常是针对该类型静态构造的。它不会被动态构造。相同的 V table 会被检测出来吗?不会,这些没有去重。事实上,它们保证不会是重复的。
[1:00:43] 如果你为两个不同的类型实现一个 trait,那么这些实现即使在代码上相同,在源代码和生成的二进制文件中仍然是不同的位置,因此会有不同的地址。涉及多个 trait 的 trait 对象我们稍后会讨论。所以 box dyn 是一个瘦指针,指向一个指向对象的宽指针。不,如果你有一个 box dyn height,那个 box 本身就是宽指针。
[1:01:22] 所以 box 是一种有点特殊的类型。实际上,它没那么特殊。只是 box 内部包含一个 mute dhinhi。而 Rust 编译器知道对于引用和指针,如果它们是 trait 对象,它们实际上是宽 2。所以 box 并不特殊,但指针类型是特殊的。所以 box.dynhi 本身就是宽的。你不会得到额外的间接层。是的,我们也会讨论 trait 对象的 nightly API。
[1:02:13] 好的,所以我认为我们现在已经到了大致能理解的程度。所以 trait 对象比完全泛型受到更多限制,有几个原因。例如,让我们想象你想要有一个……hubfn baz,它接受一个 s,这个 s 是 dyn,比如说,hi 加上 sref stir。
[1:02:58] 然后我们要做 s.hi。然后我们还会说,让 S 是 S 点 S ref。然后我们再次做 S 点 high,因为我们知道字符串本身实现了 high。我想也许这有点令人困惑。也许我应该只做 len。编译器在这里说,哦,这是有歧义的。好吧,让我们消除歧义。这与讨论并不真正相关。
[1:03:33] 它还是不允许我这么做,为什么不行?我是不是必须这样做才能避免歧义?不,好吧,我就先假装这个语法能正常工作一下。所以基本上我想说的是,我想要一个包含两个不同 trait 的 trait 对象。这实际上并不能编译通过,先忽略解析错误,其实它不能工作还有一个更大的原因,那就是:要让这个工作,我们需要知道 high 方法在哪里,以及 asref 方法在哪里。
[1:04:18] 但它们包含在两个不同的虚函数表里。一个是具体类型的 high 的虚函数表,另一个是具体类型的 asref 的虚函数表。所以我们实际需要的不是一个两宽指针,而是一个三宽指针。一个指向数据的指针,一个指向 high 的虚函数表的指针,还有一个指向 asref 的虚函数表的指针。这是可行的。从本质上讲,这并没有什么不可能,但这意味着随着你添加更多 trait,这个引用的大小会不断增长。
[1:04:55] 而这可能并不是你想要的。你可能会说,编译器就不能为这个组合生成一个虚函数表然后传进去吗?理论上它是可以这么做的。Rust 编译器目前并不这么做。我不知道有这样的提案。部分原因是你可以通过声明 pub trait high azref 来绕过这个问题,它要求类型同时实现 high 和 azref str,并且自身没有方法。
[1:05:28] 现在,我就可以这么做了。对吧?因为现在只有一个虚函数表,这个虚函数表就是 high asref,编译器知道当它需要为这个 trait 生成虚函数表时,要包含这两个 trait 的所有方法。所以这个虚函数表会更大,因为它会同时包含 high 方法和 asref 方法。所以,我认为这没有在 Rust 本身中实现的部分原因,是因为你可以自己选择这么做。通过不自动把加号变成一个更大的虚函数表,你基本上是在告诉开发者,这可能并不是你的本意,但如果确实是,你可以改用这种做法。
[1:06:12] 我同意这里的编译器错误本可以更好一些,对吧?也许我们可以告知……人们可以在这里生成自己的 trait。我记得有人写过,好像是 i plus s ref。
[1:06:52] 搅一搅,看看是不是真的。是的。好。所以,这就是获得正确编译器错误的方法,即只有自动特征才能用作特征对象中的附加特征。而这里你有一个例子,两个不同的特征,它们都不是自动特征。我们稍后会讨论这个。而这里它确实给出了我们谈到的建议,对吧?考虑创建一个新特征,将所有这些作为超级特征,并在此处使用该特征。它还指出,像 send 和 sync 这样的自动特征是可以的。
[1:07:27] 基本上这里的想法是,对于标记特征,比如如果我想说 high 加 send,send 没有任何方法。所以 V 表为空是可以的。因此我们不需要存储 V 表的额外部分,因为里面没有任何方法。所以这就是为什么可以有带无方法的附加特征。我不认为你可以使用自己的。比如如果我做一个 Fuchs 特征,我说这个加 Fuchs,我不认为那会工作。
[1:08:00] 但有一些提议,有一个标记注解来声明一个特征永远没有方法。但这不是我们目前拥有的。所以至少目前,这是你应该做的方式。很好。
[1:08:34] 好的。所以这就是特征组合的工作原理。但这不是特征对象有点受限的唯一例子。所以另一个是,让我们想象一下,对于 high,我们添加了一个,实际上,让我们从说我们添加了一个关联类型开始。我们叫它 name。我们实际上没有用它做任何事情,我们只是添加一个。代码已经无法编译了。为什么无法编译?
[1:09:05] 嗯,关联类型的值……哦,那是实现。让我来做。所以这将是 type name 等于 unit。就用这个给两者,因为我们实际上不关心类型。是的,所以这里说来自特征 high 的关联类型 name 的值必须被指定。所以这里说在我们取一个 dyn high 的地方,我们实际上需要指定关联类型。
[1:09:39] 我们不能只是说我们取任何 high,不管它的关联类型是什么。这里的原因是因为那个信息无法在 V 表中捕获,因为这是一个类型。它在二进制中没有地址。它没有任何我们可以放进 V 表的东西。因此,这不能直接与特征对象一起工作。相反,你必须说的是我取一个 high,其中 name 是这个。我想我们需要在这里做同样的事情。
[1:10:15] 然后这样就行了。因为现在我们有了一张专门针对任何实现了 high 且关联类型为 name 的类型的 V 表。所以这没问题。让我们撤销这个改动,因为它不是一个很有趣的变更。另一个可能更有趣的情况是,假设我们想要一个……我们叫它什么好呢?我们叫它 weird 吧。我们要有一个什么都不做的 weird 函数。
[1:10:48] 没有人需要实现它。你会看到这同样无法编译。cargo check 报错。让我们把这个缩小一点,希望这样能更容易理解。希望它仍然可读。哦,这太冗长了。让我把组合 trait 那部分注释掉,让错误信息稍微好看一点。好了,所以这里说 trait high 不能被做成对象。
[1:11:24] 所以当我们说 dyn high 时,基本上它是在告诉我们 high trait 不是对象安全的。也就是说,它不能被转换成 trait 对象。它说,一个 trait 要成为对象安全的,需要允许构建 V 表,以便调用可以被动态解析。这就是我们到目前为止一直在讨论的内容。特别是这里说,该 trait 不能被做成对象,因为关联函数 weird 没有 self 参数。不过它并没有真正说明为什么这是必要的。但让我们试着梳理一下。
[1:11:56] 那么再说一次,假设在我们下面的 sayHi 里,对吧?我们现在尝试调用 s.weird。那么想象一下,如果我们写了这段代码,编译器会怎么做?嗯,我们其实没法写这段代码,对吧?因为 weird 不接受 self。它不接受任何指针。我们也不能随便构造一个指向它的指针,因为那意味着我们需要有一个有效的实例才能有指向它的指针。
[1:12:28] 所以这实际上就是在说,hi 冒号冒号 weird。不用我说你也觉得这很奇怪,因为我们在这里是对哪个类型调用 weird 呢?这里没有任何东西指定我们想要哪个具体的 weird 实现。在这个特定情况下,因为它提供了默认实现,你可能会觉得这不是问题。但如果有一个针对 string 的 weird 实现呢?
[1:12:58] 它和 trait 上的那个不同,这是允许的,对吧?你可以覆盖默认实现。那么这怎么知道该调用 str 的那个、trait 的默认那个,还是某个完全不同的实现呢?它不能放在 V 表里,因为这里没有 S,对吧?weird 方法不接受自身。它不与任何类型的任何给定实例关联。所以这根本行不通。说这个没有意义。
[1:13:32] 但如果你真的想要这样呢?比如你希望这个奇怪的函数存在,但你说,我不在乎通过 trait 对象来调用它。我只关心 high 那个东西。通过 trait 对象。所以我希望 high 是 trait 对象安全的,但如果你有一个 trait 对象 high,即使你不能调用 weird,我也没关系。所以你可以这样做。这样。
[1:14:09] 让我回到下面这里,再次让 high 里有 speed,s 点 a。所以这里我们要说的是,weird 函数要求 self,也就是实现该 trait 的类型,是 sized 的。我们记得 trait 不是 sized 的。如果你只有像 dyn high 这样的东西,那不是 sized 的。只有当它在指针类型后面时才是 sized 的。
[1:14:43] 所以这基本上是一种退出 V 表的方式,你可以这样理解。它是在说这个函数不应该被放进 V 表,而且关键的是不应该能通过 trait 对象调用。这意味着在这里,让我把静态版本去掉,因为它们只是碍事。这意味着现在代码可以正常编译了。我可以调用 hi,我可以为它创建一个 trait 对象。但如果在里面,事实上,我甚至可以更进一步说,假设这个确实有 self,但我想退出。
[1:15:22] 那么这仍然可以编译,我仍然可以为它创建一个 trait 对象。但假设我尝试在这里调用 weird。编译器会告诉我 weird 方法不能在 trait 对象上调用,因为该方法有 sized 要求。所以这就是让任何给定函数退出被包含进来、以确保该 trait 保持对象安全的方式。你也可以通过写 where self 是 sized 来声明整个 trait 不应该能被转换成 trait 对象。
[1:16:01] 所以如果你这样做,你基本上就是禁止把这个 trait 用作 trait 对象。在实践中很少见到这种情况。通常 trait 只是因为其中的方法而不是对象安全的。主动选择禁止 trait 对象是很少见的。有时人们这样做是为了……向后兼容的原因。比如如果你知道你以后可能会添加非对象安全的方法,你可能会主动加上这个,但这相当少见。
[1:16:36] 好了,到目前为止这些限制说得通吗?关联类型的问题在静态分发时也会出现吗?不,不会。原因是使用静态分发时,因为它会被单态化,你实际上知道任何给定函数实现的具体类型。s 冒号冒号 weird 是可能的。
[1:17:10] 所以这是在我们还有 fn weird 的时候,对吧?假设我们这里还有一个 override。现在假设你希望能够,比如说我们添加了这样的特殊语法,表示对于 s 类型调用 weird 方法。你可以想象 weird 被包含在 trait 对象的 vtable 中,但它知道不要用 self 参数来调用它。这里的挑战在于这有点奇怪。
[1:17:45] 如果你调用它本来就需要该类型的一个实例,那它为什么不直接接收 self 呢?传统的例子是 weird 实际上叫 new 或类似 new 的名字,对吧?在这种情况下,如果你已经有了该类型的一个实例,你根本不需要调用这个方法。它直接接收 self 就行了。所以我同意类似这样的东西也许是可行的。但我认为在实践中,它通常不太有用。
[1:18:19] 这就是为什么它一直没有被优先考虑。可能还有更深层的原因导致它没有被加入。我不确定。嗯,那么 where self: Sized 是否也禁止为具体的 DST 实现该 trait 呢?你知道,这是个好问题。所以问题基本上是,如果你有 where self is Sized,我能为 Box
[1:18:58] 比如说。我相信可以。我说这应该可行的原因是,是的,现在这不行了,因为它不能作为 trait 对象,但我相信你仍然可以有这个实现。为什么会这样?哦,对了,因为它是 Box。所以我们需要双重引用。这没问题,因为这不是动态大小的类型。
[1:19:35] 再说一次,当你把它包装在指针后面时,它现在就有了大小。它不是动态大小的。所以即使 trait 上有 self-sized,也不会阻止这一点。关联类型的限制感觉很奇怪,因为关联类型的意义在于对于任何给定的具体类型只有一个存在。那么 vtable 不应该知道关联类型应该是什么吗?比如,它不能有指向该类型的指针,但 trait 的实现应该在编译时知道该类型是什么。
[1:20:07] 是的,所以问题在于类型被擦除了。剩下的只有 vtable。所以你无法从 vtable 中判断出原来的具体类型是什么。有一个例外,就是 any trait。any trait 有一个方法返回……将原来具体类型的描述符转换出来。如果你没跟上,没关系。忽略它。但基本上,有一些方法可以绕过这个问题。但基本上,trait 对象是类型擦除的。
[1:20:38] 就像你无法保留它曾经是的那种类型的信息。哦,你是指像 str 或 u8 这样的类型。不,你不能那样做。当你有 where self is sized 时,Self 必须是 sized 的。TraitObjects 还有一个限制,就是方法不能是泛型的。对于这一点,与其继续研究我们那个奇怪的高阶 trait,我实际上要去标准库看看 fromIterator trait。
[1:21:16] 所以 fromIterator trait 是例如 Vec 实现的东西。这就是 collect 的工作原理,即 Vec 实现了 fromIterator。而当你拥有,好吧,如果我们看看 iterator 的 collect,我想这是最好的方式。对迭代器调用 collect 要求收集到的目标类型实现了 from iterator。所以这就是为什么你可以有一个迭代器并收集到一个 vec 中,因为 vec 实现了 from iterator。不过 from iterator trait 有点奇怪。该 trait 的 A 类型是迭代器项的类型。
[1:21:55] 但你也看到 from iterator 类型本身接受一个 T。这里的 T 是迭代器的类型,对吧?因为它必须是 Vec,例如。它不关心迭代器是什么。它可以是,它可以,你可以从任何类型的迭代器构造一个 vec,只要,好吧,你可以从任何项为 T 的迭代器创建 vec T。这可以说应该叫 I 代表 iter,但这并不太重要。这里,A 是你最终会得到 vec 的那种东西。
[1:22:30] 所以如果这个 A 是,比如说,bool,你最终会得到一个 bool 的 vec。而 T 是迭代器的类型,可能是类似,我不知道,像 HashMap 迭代器之类的最终类型。不过这对 Trait 对象来说是个问题。让我们想象一下我们尝试针对这个写代码。所以我要先把这里擦掉一下。事实上,我要写一个新的。擦掉这个文件剩余的所有内容。然后我要有,我们在这里要做什么,让我们做 collect。
[1:23:09] 标准的 iter from iterator,我们要取一个 from iterator of bool。然后我们要返回一个 vec of。然后我要做 s 点 collect。哦,我做了什么?我做了些奇怪的事,对吧?太好了。所以这看起来应该没问题,对吧?我接受任何能,我接受。
[1:23:42] 嗯,实际上,这因为多种原因很奇怪。也许 fromIterator 在这里是个糟糕的例子,因为它也不接受 self。所以它实际上无论如何都要求 self 是 sized 的。Extend 是更好的一个。让我在这里找一下 extend。太好了。所以我们要改用 extend。它将必须接受一个可变引用。所以我们要做那个 mut v 是 back new,然后我们要做 v 点 extend。
[1:24:18] 实际上,我们甚至不打算那样做,我们将把这个作为 V,我们将执行 v dot extend,并且只给它一个 true。所以我们将用一个单一的布尔值来扩展它,添加 true。因此,我们接受任何可以用布尔值迭代器扩展的东西。然后我们尝试用一个产生单个布尔值的迭代器来扩展它。
[1:24:49] 所以我们只是要添加 true,我们要把 true 追加到我们得到的任何东西上。这里也一样,它告诉我们 trait extend 不能被做成对象,因为 extend 不是对象安全的。如果我们看看 extend,从我们目前所看到的来看,这并不能立即说得通。对吧?所以再次,它在迭代器项的类型上是泛型的。这没问题。Extend 接受 self。所以我们确实有可以放进 V 表的东西。给定一个实例,我们大致知道如何调用这个方法。但再次注意,它在迭代器的类型上是泛型的。
[1:25:23] 这就是它变得非常奇怪的地方。你可以想象,就像在 vec 内部,对吧,会有 impl t, extend t for vec t。它将有这个实现。我将继续称它为 I,因为我认为这样更有帮助。谁知道这里面会有什么,对吧?
[1:25:58] 是的,只是为了消除那个警告。呃,我要这样做。嗯,我想这会更有帮助一些。我的 vec。就像这个实现会存在于标准库的某个地方,对吧?只不过是为 vec 而不是。但这个方法 是泛型的。所以我们从单态化的讨论中知道,实际上在编译时,我们最终不会得到一个单一的 extend。
[1:26:35] 我们最终会得到这个方法的多个副本。对吧?我们最终会得到一个 extend 规则,它接受……现在,一个 extend,我想,HashMapIntoIter,它接受一个标准集合 HashMapIntoIterator。对吧?事实上,甚至不止于此,我们实际上最终会得到,因为整个 impl 是泛型的,我们实际上会有这个。
[1:27:13] 那就是实际被实现的方法。或者说是由编译器生成的,假设有人尝试使用布尔值的 HashMap 迭代器进行扩展。不存在单一的 extend。对于迭代器和项类型的每一种组合都有一个。那么放进 V 表的是什么?我们已经确定了我们想要 extend bool。
[1:27:44] 所以这很好,对吧?所以这里只有,我们不必考虑上面的 T,因为我们已经选定了那个 T。但对于 extend 本身,在 V 表里,我们确实需要有一个指针,指向针对 bool 的迭代器类型的 extend 实现。但这并没有体现在函数的类型里。我们甚至没有办法表达它。对吧,你可以想象一下,比如 extend 的这些实现是标准 iter once 之类的,或者某种非常奇怪的东西。
[1:28:26] 但按照现在的写法,这里没有任何东西表明我们希望 V 表指向标准 iter once 的 extend 实现。问题就在这里。当编译器尝试生成这段代码时,没有指向 extend 适当实现的指针。因此,V 表无法生成。你无法为 dynExtend 生成 V 表,因为它会有无限多个条目,每个可能的 extend 实现对应一个。
[1:29:02] 因此,答案就是 dynExtend 不能存在。你无法为 extend 创建 trait 对象。好,这说得通吗?这个解释有点复杂,但希望这些内容能串起来。嗯,Rossi 能不能为每个调用 extend 时传入的 T,向每个实现了 extend 的类型添加一个单态化的 extend 版本?这很诱人,但并不总是可行,对吧?
[1:29:36] 所以想象一下你在编译这段代码,但是,嗯,我的意思是,即使只是标准库,对吧?标准库有很多地方用到 extend,但在依赖那个 crate 的 crate 里,它们可能会用更多类型调用 extend。所以 V 表的大小,比如当你编译最底层的 crate 时,可以说是标准库,这基本上意味着标准库里 dyn extend 的 V 表与各个 crate 里 dyn extend 的 V 表不同。
[1:30:12] 更上层的其他 crate 也是如此,因为可能有更多你想使用的迭代器实现。于是你现在会得到许多不同的 vtable 实现,或者许多不同的 dynExtend 的 vtable。这就像是一种组合爆炸的问题。而且这也意味着你不能把标准库里的 dynExtend 传给更上层 crate 里接受 dynExtend 的东西,因为它们的 vtable 类型不同。好。
[1:30:54] 所以这就是为什么你不能拥有…… 要让一个 trait 成为对象安全的,它需要…… 不能有泛型方法。它需要,它的所有方法都需要有一个包含 self 的接收者。还有另一个要求,就是这个 trait 不能有一个返回 self 的类型。所以如果我们在这里稍微回溯一下,说 clone,我们想拿一个 dyn clone 的东西,我们就直接调用 clone,因为这是我们对 dyn clone 唯一能做的事。
[1:31:37] 对吧?如果你有一个 dyn clone,你实际上只能做这个 trait 允许你做的事,而 clone 唯一允许你做的就是 clone。所以这说明 clone trait 不能被做成对象。这是我们现在已经见过不少次的错误。你不能这样做的原因是 clone trait 对吧,有一个 fn clone,它接收 self 并返回 self。好,那假设我说 let x 是 v.clone。x 的大小是多少?dyn clone 就是任何可克隆的类型。
[1:32:16] 它应该返回 self,而不是引用。所以它不应该返回一个引用 DynClone。它应该在给定引用的情况下返回 self。所以这某种程度上意味着它应该返回 DynClone,因为这里的 self 就是这个。因为我们已经擦除了具体类型。但 DynClone 不是 sized 的。所以这意味着这个方法的返回值不是 sized 的。而一个……函数的返回类型必须是 sized 的,我们才能为它生成代码。
[1:32:49] 因此,这行不通。所以你不能有返回 self 的方法,才能让一个 trait 成为对象安全的。这就是为什么你不能做 clone。现在,有些情况下你有一个 trait,就像我们讨论 high 时说的,你可能有一些方法是对象安全的,并且单独使用仍然有用,但你还有一堆其他方法会让这个 trait 变成非对象安全的,但你想要为那些不经过 trait 对象的类型包含它们,只是因为这样方便。
[1:33:23] 事实上,一个很好的例子是如果我们看 iterator trait。所以 iterator trait…… 对吧,有关联类型 item,那没问题,它有 next,而 next 是对象安全的,但它也有一堆方法,比如 chain 是泛型的,它有 enumerate 返回 self,它有 by_ref,返回 mut self。
[1:33:56] 它有 collect,它依赖于 from iterator,我们已经知道那不是对象安全的。那 iterator 怎么能是对象安全的呢?因为它确实是。如果我在这里说,我说我想拿一个 dyn iterator,其中 item 是 bool,我们 collect。哎呀,iterator。好吧,我不能调用 collect,因为这个方法不能在 trait object 上调用。
[1:34:30] 但我可以调用 next。我允许在这个上调用 next。静音,否则它就不起作用。这样没问题。而迭代器 trait 实现这一点的方式是,如果你仔细观察,你会发现,如果我真的去看迭代器 trait 的源码,你应该会看到这个,你就在这里找到。
[1:35:03] 比如 count,它会消耗 self,对吧?所以它不允许放在引用后面,那会使其成为 sized,带有 where self 是 sized。如果你向下滚动到 last,也是一样,self 是 sized。如果我们看 chain,你会看到 chain,它是泛型的,所以通常会使 trait 非对象安全,带有 where self 是 sized。这样做的原因是,你基本上可以,这和我们为那个奇怪函数做的一样,对吧?你可以使用 where self 是 sized 约束来说,为了将这个 trait 用作 trait 对象的目的,忽略这个函数。
[1:35:41] 基本上,不要试图把它放进 V 表。这意味着如果有人有一个 trait 对象,他们就不能调用这个方法。但如果他们没有 trait 对象,如果他们实际上有比如一个 vec 迭代器或者他们有具体类型,那么他们就可以调用这个方法。所以这是一种方式,让一个 trait 有一些好用的方法,但如果不让整个 trait 对象变得非对象安全,这些方法就不会是对象安全的。嗯,接收者可以是任何包含 self 的东西,还是必须是 ref self 或 mute self?
[1:36:16] 嗯,所以这方面的规则实际上是,呃,我在哪里有这个?我在某个地方开着它。给我一秒钟。这里。所以这是来自 Rust 语言参考中关于对象安全的部分。事实上,到目前为止我们已经涵盖了大部分这些内容。所有超 trait 也必须对象安全,对吧?因为我们从所有超 trait 的并集构造一个 V 表。Size 不会是超 trait。
[1:36:47] 所以那就是,如果我们要求 self 冒号 sized,它就不是对象安全的。不能有任何关联常量。这又是因为。你没有地方放这些常量。理论上,也许你可以把它们放在 V 表里,但现在 V 表变得非常大。而且 V 表里的值也不再都是像函数指针那样的东西。它们可能是任意大小的东西。所有关联函数必须要么可以从 trait 对象分发,要么被明确标记为非可分发的。
[1:37:19] 所以可分发函数要求它们没有类型参数,因此它们不是泛型的。它们必须是不使用 self 类型的方法,对吧?具体类型,除了接收者的类型之外。所以例如,我们不能有返回 self 的东西。它不能有除以下类型之外的接收者,对吧?所以它可以是对 self 的引用,可以是对 self 的可变引用,可以是 Box
[1:37:55] 你可以看到这明确排除了 where Self: Sized 约束,这样即使某些方法不是对象安全的,你也可以拥有一个对象安全的 trait。这些是不可分发函数。嗯,库作者是否应该总是考虑为非对象安全的方法添加 where Self: Sized,以防下游有人想将其用作 trait 对象?我认为应该。嗯,这在一定程度上取决于你的 trait 是否可用。
[1:38:28] 所以如果你的 trait 不能用作 trait 对象,比如想想 Clone,对吧?那么当然,你可以为 clone 方法添加 where Self: Sized,这样人们就可以创建 trait 对象 clone,但他们甚至无法调用该 trait 的主要函数。所以这 probably 不值得。但我确实认为,一般来说,如果你有一个 trait,它是有用的,即使你……只能调用对象安全的方法,那么为其他方法选择退出可能是有意义的,这样整个 trait 就是对象安全的。
[1:39:14] Iterator 的 last 有 Sized 限制吗?我认为 Iterator 的 last 有。嗯,last 有 where Self: Sized 的原因,你在这里看不到。它被 rustdoc 隐藏了,嗯,是因为它的接收者。它不在引用后面。它消耗 self,嗯,这意味着它接受 self,嗯,而 Self 是一个非 Sized 的迭代器,并且函数参数必须是 Sized 的。
[1:39:47] 因此 last 不能通过 trait 对象调用。还有一件事我还没告诉你。嗯,有很多事情我还没告诉你,但至少有一件关于 trait 对象的事,那就是 trait 对象有一个小秘密。所以假设我有 pub trait。实际上,我们这样做吧。Drop 实际上是对象安全的。
[1:40:19] 你可能会觉得这很奇怪。就像如果一个对象你唯一能做的就是丢弃它,那它真的有那么有趣吗?事实证明,这在几种情况下很有用。比如,我知道 Crossbeam 就这么做,例如,你想做垃圾回收,但又不想立即丢弃对象。你想把它们放进一个链表之类的东西里,然后定期去收集所有垃圾。因为你想在一个类型中存储许多可能不同的东西,所以你需要 TraitObjects。因此它只是把 mut 放进 drop 里,或者我认为技术上说是把 boxed 放进 drop 里,但效果相同。
[1:40:56] 你实际上无法用这个做任何事。但在这里,当 v 离开作用域时,dropDrop 会通过 btable 被调用。这应该让你想,等一下,因为我们拿 sayHi 来说。我们取 dinAsRef.stir。或者实际上,我们甚至拿 boxed 来说。
[1:41:30] 这样更好。当 s 离开作用域时会发生什么?想一想。我们得到一个 box,所以我们在堆上有一个内存分配。我们可能在这里使用它,可能调用 s.asref,这可能是 high,随便什么。但然后当这个函数返回时我们丢弃 s。但当我们丢弃一个 box 时,我们必须释放内存。但这是一个 trait 对象,所以它唯一有的方法是 asref。
[1:42:06] 这个问题的答案是每个 Vtable 都包含 drop。你可以把这想象成这里有一个隐式的 drop,但在实践中,任何 TraitObject 的 Vtable 都包含一个指向具体类型的 drop 函数的指针,因为这是必要的。它技术上还包含一点额外信息。它包含具体类型的大小和对齐。这些之所以在里面,是因为对于像 box 这样你必须释放内存的东西,这些信息是必要的,要传给分配器来做释放。
[1:42:44] 所以每个 trait 对象都包含 V,或者说每个 trait 对象的 V table 都包含该 trait 的方法加上 drop 加上大小加上对齐。通常,你不必考虑这个,但既然我们谈到这个话题,了解一下是值得的。稍微换个话题,到目前为止我们只真正讨论了 trait 对象,但还有其他类型不是 sized 的。例如,我们知道 din trait 不是 sized 的,但 u8 也不是 sized 的,而 str 也不是 sized 的。
[1:43:20] 当你把它放在引用或指针后面时,它会被转换成一个元组,包含指向数据的指针和指向虚表的指针。而如果把它变成有大小类型,或者放在指针后面,它也会变成一个宽指针,其中一部分是指向数据的指针,另一部分只是一个 usize,即切片的长度。str 也是一样,一个指向数据的指针加上一个表示长度的 usize。
[1:43:57] 所以这就是为什么,如果你尝试写一个接受 u8 的函数 foo,编译器会冲你大喊,说类型 U8 的值的大小未知。因为 U8 只是表示一个任意长的 U8 列表,它是没有大小的。因此我们不能用它作为参数来调用该函数。就像你尝试直接返回一个 U8 序列一样,对吧?如果我有一个 bar,它返回一个 U8。
[1:44:33] 嗯,它也会报错。哦,呃,它甚至让我这么做吗?好了。我构造了这个类型。所以这里它说了同样的话。类型 U8 的值的大小无法得知,而函数的返回类型必须具有静态已知的大小。所以这是同样的问题。这里也一样,我们从没有大小的东西变成有大小的东西的方式,是把它放在一个能够掩盖无大小性的类型后面,你可以用引用做到这一点,也可以用 box。
[1:45:14] 所以你也可以对它使用 box。我想这是允许的。很好。所以这没问题,因为它现在有大小了。它的大小是一个宽指针,其中一部分是数据,另一部分是长度。嗯,然后编译器就知道,当你访问这个类型时,它知道要解构这个指针来获取长度。
[1:45:51] 嗯,对于 box 或原始指针也是一样。对于 string 也一样。所以这些有点神奇。已经有一些工作试图将其标准化。所以目前这些动态大小类型在编译器中有点特殊,因为你需要知道指针是否是宽的。所以自己处理无大小类型是相当困难的。比如,如果你想自己实现 box 并接受一个无大小的类型,这是可能的。
[1:46:27] 一旦涉及到类型转换和允许 trait 对象之类的东西,就会变得相当烦人。但最近有一个 RFC 落地了。RFC 编号 2580。它讨论了添加一个通用 API 来操作胖指针的元数据。所以这让你可以做诸如指定胖指针第二部分类型之类的事情。对吧。所以在这种情况下,实际上,我们可以在这里往下滚动一点,看看一个 DIN trait 现在变成了一个 pointy,其中元数据是 DIN 元数据。
[1:47:09] 而我们是 DIN 元数据。它是指向 Vtable 的指针,该 Vtable 表示所有信息,例如类型大小、类型对齐、指向 drop 和 place 的指针,以及指向该类型所有方法的指针,用于简化 trait。所以正是我们刚才谈到的内容。同样地,你可以想象这个 pointy trait 会为类似不带引用的 U8 切片实现,其中元数据是一个 U 大小,即该对象的长度。
[1:47:44] 这仍然非常像新事物和实验性特性。我确实建议你通读这个 RFC。如果你想了解更多,它真的非常有趣。它包含诸如 trait 别名 thin 之类的东西,即任何实现了 pointy 且元数据为空的类型,也就是任何在指针中没有关联元数据的类型,因此是任何瘦指针而非胖指针。它本质上还提供了用于内省指针元数据的方法,这样你就可以做诸如实际查看 Vtable 之类的事情。
[1:48:16] 之前聊天中对此有一些问题。这个 RFC 实际上会让你内省这些信息,并且关键的是在运行时动态构造 Vtable。因此你可以有一个在编译时未知但在运行时构建的 Vtable。事实上,据我所知,这已经是标准库中某处存在的东西,即用于异步领域中的 waker。所以 waker trait,我们不打算深入细节,但 waker trait,我会在这里展示给你看。
[1:48:48] 嗯,那个 waker,我说错了。我是说 wake trait,呃,awake,不是 wait,是 raw waker。哦,它没有对应的 trait。这就是为什么,嗯,让我们实际给你展示 context。所以 context 给你一个 waker。Waker 是一个结构体,具有 wake、wake by ref、willWake 和 fromRaw 这些方法,并且你可以 drop 和 clone 它。
[1:49:24] 但在实践中,waker 实际上非常泛型。只是当你看着它时它并不泛型。但在 waker 内部是一个 raw waker。而 raw waker,如果你看它的内部,是一个数据指针和一个 vtable 指针。所以它确实是一个数据指针。是动态分发,但以一种隐藏的方式,而 vtable 是一个 raw waker vtable,你通过为 clone 方法、wake 方法、wake by ref 和 drop 提供函数指针来构造 raw waker vtable。
[1:50:03] 所以这基本上就是一个手动构造的 Vtable,它通过类型而不是 trait 为你提供动态分发。我不打算深入讲太多细节,我只是想把它作为标准库中手动构造 Vtable 的一个例子展示出来。从这里我还想再讲点什么吗?我觉得没有了。好,我们来做问答吧,因为我已经讲了一会儿了。
[1:50:38] 我以为对 U8 的引用有一个起始指针和一个结束指针,而不是一个长度。我觉得它是有长度的。它没有,这两者基本上等价。你可能是对的,我忘了。事实上,我想知道这个引用是怎么说的。是的,你看,这个 RFC 也废弃了 Trait 对象。那些在 Nightly 中存在的东西,因为这是一个替代方案。
[1:51:11] 尖头 trait、瘦元数据、从原始部件构造。……的定义在哪里?哦,它实际上没有给出。是的,我本来希望它会在这里说明切片实际的关联元数据类型是什么,但我没看到。
[1:51:42] 我觉得就是长度。我们能创建自己的动态大小类型吗?算是可以。所以你可以这样写。这里的 foo 现在不是 Sized 的。事实上,你可以添加更多字段。但你不能在这之后添加字段。在这之后它就不是 Sized 的了,对吧?
[1:52:14] 所以如果我尝试这样做,它会告诉我 u8 的值的大小无法在编译时得知。只有结构体的最后一个字段可以具有动态大小类型。将字段类型改为具有静态已知大小。借用类型总是具有静态已知大小。所以这里想说的是,如果它是最后一个字段,那就回想一下我一开始提出的论点,对吧?如果你在这里中间有一个非 Sized 类型,然后我问你,如果我想查找 foo.x,而你只有一个指向 foo 的指针,当中间的类型可以有任意大小时,你怎么得到一个指向 x 的指针?
[1:52:54] 答案是你做不到。你不知道如何获取 x 的地址,因为 t 的大小是任意的。但如果它在末尾,那就没问题。你可以静态地知道 f 的偏移量、x 的偏移量和 t 的偏移量。而使其成为 Sized 所需的唯一信息就是最后一个字段的长度。所以你可以构造这样的类型。这个类型现在不是 Sized 的。但如果你有一个 &foo,那么那个类型将通过存储指向 foo 的指针以及 t 的长度而成为 Sized 的。
[1:53:34] 所以你可以用这种方式创建自己的动态大小类型。Box
[1:54:05] 它们并不相同。它们感觉相同,但实际并不相同。哎呀。Vec 可以增长。所以首先,Vec 有三个词。它是指向堆上 vector 的指针。它是 vector 的长度,也是 vector 的容量。这样做的目的是,如果你尝试在容量范围内 push,长度只会递增。如果你尝试 push 超出容量,那么整个 vector 会重新分配、复制过去,然后改变。
[1:54:39] 对于 Box U8,你无法那样做。它永远不会增长或缩小。你不能向它推入元素。它只是,可以把它看作一个,它真的只是一个切片。你可以把 Vecuate 转换成 Boxuate。你也可以反过来做。但它们并不相同,不。dinfn 和 fn 之间有什么区别?
[1:55:28] 所以基本上,我可以写一个 fn foo,它接受一个 dyn fn。我也可以写一个 fn bar,它接受一个 fn。这两者之间有什么区别?它们并不相同。这必须是一个函数。它不能是闭包。原因是 fn 实际上是一个函数指针。
[1:55:59] 就像它只是一个指针,必须是一个地址。这是一个 vtable。它是一个 trait 对象,这意味着它既有你可以在这里想到的 vtable,其中有一个指向……调用函数的指针,但它也有一个数据指针,对吧?因为 V,它的结构是一个宽指针,其中一部分是 V table,它包含实际调用函数的指针,但另一部分是数据指针。而关键的区别在于,如果我有 fn main,我可以用闭包调用 foo。
[1:56:41] 所以我可以传一个函数。这样,但我不能用 bar 做同样的事。为什么它在报错?哦。对了,所以我可以用闭包调用 foo,因为它捕获了 x,对吧?
[1:57:16] 所以它不仅仅是一个函数指针,它是一个函数指针加上闭包从其环境中捕获的数据。也就是说,它需要,当你调用闭包时,你还需要提供 x 的地址,因为闭包的主体需要它。这就是宽指针的数据部分所传递的内容。对于 bar,它要求一个真正的函数指针,这意味着你不能传闭包,因为你没有地方存放数据。当我们使用 dyn fn 而不是 impl fn 时,是的,所以还有 baz f impl fn。
[1:58:03] 嗯,我可以用闭包调用 Baz。它是什么?它在报什么错?我可以用闭包调用 baz,因为记住,impl fn 是对任何是 fn 的东西的泛型函数的语法糖。
[1:58:34] 因此,对于传入的每一种闭包类型,我们实际上都会得到一个具体的 baz 副本。因此,你也可以轻松地传入数据,因为它对每个单独的闭包都进行了单态化。那么问题就变成了,什么时候使用 dinfn,什么时候使用 implfn?基本答案是…… implfn 更具通用性。比如,你不必通过指针进行间接访问。但你最终会为传入的每种闭包类型生成一个 Baz 副本,这可能会变得相当多。
[1:59:12] 另一个原因是,有时你想使用 trait 对象而不是使其泛型化,因为否则你必须将泛型类型向上传播。所以想象我有一个……结构体包装器,然后内部我希望它包含一个函数指针。如果让它持有,比如我可以这样写,对吧?我可以这样做,但这意味着任何想要使用我的库、想要持有包装器的人,他们自己也需要对 f 泛型化,或者命名 f 的类型。
[1:59:51] 而如果这里改为存储一个 box din fn,那么包装器就不再是泛型的,所以我的调用者不必考虑和传播那个泛型参数。所以有时它能清理你的接口,使其更易于使用。还有 trait 的例子,使 trait 对象安全。所以如果我有一个 trait x,它有一个 fn foo,如果我让它接受 impl fn,那么 x 就不是对象安全的。
[2:00:28] 我无法写一个 crocs。我想让这个接受 self。trait x 不是对象安全的,因为这是泛型的。implfn 等价于说 f 是 fn,而这是 f。
[2:01:01] 而这不能像我们讨论的那样被做成对象安全的。但另一方面,如果我把它做成 dinfn,它可以是对象安全的,因为只有一个 foo,对吧?所以我们没有这个问题,即你需要在 V 表中有无限数量的条目,只有一个 foo,它本身接受一个宽指针,然后对任何可以是对象安全的类型都有效。所以这里没有明确的答案。嗯,不错。
[2:01:49] 好的,我想,我想这涵盖了……我想谈论的一切。所以我们没有谈到的一件事是一致性。我认为一致性足够不同,我们不会在这个直播中讨论它,我可能会单独做一个关于它的直播,特别是因为我们已经到了大约两个小时的标记。所以我认为这是一个停止的好时机。
[2:02:22],然后单独做这个。到最后,关于我们目前讨论的所有内容,有什么问题吗?静态分派和动态分派之间的一般区别、size trait、V 表、对象安全性、宽指针和胖指针,这些现在大致都能理解了吗?或者还有什么我可以再讲一遍,帮你理清思路,让你清楚为什么要有这些、它们是做什么的、有什么限制?最后我很乐意回答一些问题。
[2:03:00] 未来能否使用某种 vtable 来实现运行时 trait 检测?如果我理解正确的话,我认为不能。所以问题是,能否拿到一个 trait 对象或一个宽指针,仅通过查看它的 V 表来判断它实现了哪些 trait?我认为不能。部分原因是,每个 trait 对象都会生成不同的 vtable。
[2:03:37] 所以并不是 str 或 string 只有一个 vtable,对吧?string 有很多 vtable。每个 dyn trait 对应一个 string 的 vtable,对吧?嗯,所以并不是只有一个 V 表,你可以通过它来判断它实现了哪些 trait。嗯,比如如果你有一个 find traits,它接收一个实现了 dyn trait 的 S,嗯,那么 V 表里只会包含你在这里指定的 trait 上的那些方法。
[2:04:24] 你不会得到一个包含所提供类型上所有可能方法的 V 表。所以不能,我认为你无法通过这种方式动态检测某个东西实现了哪些 trait。调用 dyn fn 是否涉及双重解引用,一次用于 Vtable 指针,一次用于其中的实际函数指针,还是这会被优化掉?所以如果我调用一个接收 F: Fn 的函数,并在这里调用 F。
[2:05:07] 你知道,这是个好问题。我认为最终会是双重解引用,因为你首先得经过……这并不完全是双重解引用,因为这是一个宽指针,对吧?它不是指向一个由指针和 V 表组成的元组的指针,对吧?真正传入的是一个指向某个 T 的指针。
[2:05:39] 你只是不知道这个 T 是什么,以及一个指向 T 的 Fn V 表的指针。这才是真正传入这里的东西。所以这最终会调用类似 Vtable.call of t 的东西。因此这里确实有一次解引用。比如,这是一个指向 Vtable 的指针。
[2:06:12] 所以确实需要解引用 Vtable。我觉得这是把它类型化出来的一种更好的方式。所以确实需要解引用 Vtable 才能到达调用点。我想,其实就是这个,对吧?你必须解引用 V 表来找到你要调用的那个调用的地址。所以最终确实是两次解引用,但也不完全是指针追逐。确实如此。
[2:06:58] 好,那么有一件事有点古怪,对吧?就是如果你有一个 X,它接受一个 S,比如说 dyn S ref str,那么你可以做的一件事——这在聊天中提到过——借助新的指针 Vtable 动态元数据 RFC,你可以想象,如果 s.Vtable 等于 string as dyn asrefster.Vtable,那么就像,s 作为引用 f s 点 data 作为对 string 的引用,我猜如果这是个可变……点 push,对吧,也许你可以做这种非常奇怪丑陋的魔法。
[2:08:02] 我建议干脆别这么做。但没错,你可以想象用这种方式比较 V 表。我不知道这是否能保证编译器会坚持一个类型永远只有恰好一个 V 表。而且,编译器在这里也确实做了相当多的优化。比如如果你做 box dyn FN,我想它可能并不总是做堆分配,如果你……如果只是逃逸分析之类的。但一般来说,如果你使用泛型,比如如果你使用真正的泛型类型参数,或者 impl 块,抱歉,是 impl trait,在那些情况下你会得到更好的优化,因为编译器在编译时能完全洞察所有相关类型是什么,并能基于实际的具体实现进行协同优化。
[2:08:52] 而一旦你通过动态分发进行间接调用,编译器就会失去一些它原本拥有并能据此优化的信息。你能快速举个例子,说明 dyn 的 sliceVec 吗?哦,可以。说 hi。所以如果你真的想做,比如,我想我们有 dyn hi,但让我们把它做成 dyn asref stir。然后你想要像 for H 和 S 那样。
[2:09:27] 让我们把它做成 V。对于 S 和 V,S.asref。嗯,所以要让这个真正工作,你最终要做的是这个,嗯,来让它变成 sized,对吧。嗯,这样数组的所有元素都是相同大小,因为 raise 要求如此,这样你才能找到给定的索引。对吧。嗯,一旦你这么做,嗯,salt 就自然工作了。
[2:09:59] 而且你还可以为内部类型也放一个盒子或弧或随便什么。不同的编译单元可能导致不同的虚表。听起来差不多。所以这有点轶事性质,但当你编译 Rust 代码时,Rust 可能会用多个独立线程来编译一个 crate 的不同子集,以加快编译速度。但因为你想让那些独立单元完全并发地工作,而不需要太多同步,它们可能都会遇到,比如说,一个……
[2:10:37] 字符串被用作 dyn as ref,它们可能各自生成自己的虚表,因为它们不想为生成虚表而协调,因此即使是同一类型、同一 trait,你也会有多个虚表。这就是那个不变量可能不成立的一个例子。这是个好观点。而且是的,还有 any,我还没讲过。我不会实际演示它,但确实有 any trait。而 any 非常神奇。
[2:11:09] 实际上并不是说 any 只是一个带有一个函数的 trait,该函数返回一个类型的标识符,该标识符是唯一的,由编译器保证。所以如果你有一个基于 any 的 trait 对象,你可以在它上面使用类型 ID,因为它会被添加到虚表中,以获取该值的唯一……类型标识符,然后你可以用它从 dyn any 向下转型到具体类型,因为我们知道类型标识符是什么。我不打算太深入讲 any,但 any 使用了我们到目前为止讨论过的很多东西,以便能够从 dyn 一个 trait(只要该 trait 包含 any)转换到实际底层类型的引用。
[2:12:02] 这真的很酷,而且既然你已经知道了你所知道的,它实际上出奇地简单。所以我建议你读一读标准库 Any 模块的文档。它讨论了为什么这是安全的。好了,我想我们就到这里结束吧。2 小时和 15,我对此挺满意的。我们讲了很多。我希望那是有用的。我希望你觉得你学到了一些东西,而且其中一些可能真的会记住。我在我的编码直播上取得了一点进展,我真的很想让它实现。
[2:12:36] 我希望它会尽早而不是推迟发生,但我没有忘记它。我还在跟进这件事。感谢大家来参加,我们下次见。再见,告别!
查看英文原始字幕
[0:07] Hello folks, welcome back to yet another Crust of Rust. This one, I'm hoping I didn't bite off too much to cover in like an hour and a half to two hours. I guess by the time you watch this recording afterwards, you'll see whether I succeeded or not. So for this one, what I wanted to cover was... a sort of chunk of semi-related topics around traits and dynamic and static dispatch, the size trait, like wide or fat pointers.
[0:44] And some of the things around like V tables, coherence, they all have this kind of dynamic and static approach to them. They're all sort of tied together, some more so than others. And I get a lot of questions about each one. And I figured I should just do one stream where we talk through how all of this stuff works and how it fits together. I'm hoping that we don't... end up too far down any one rat hole. I think what I'll try to do is cover most of it in sort of workable detail.
[1:18] And then we might do sort of a deep dive on one of them in some later stream. But in order to try to contain it to the time, you might find that I skip over some of the detail, and hopefully that'll be OK. So I actually wanted to start this time on The Rust Book. So The Rust Book has a chapter on generic types and traits and lifetimes. And there's this one subsection in there on the performance of code using generics. And this is a section that, if you've read the book, and I highly recommend you do if you haven't already, might have struck you as, you might have read it and be like, that sounds like magic.
[1:59] And in some sense, what this stream is about is trying to deconstruct that magic and figure out what's inside. And in particular, it talks about this idea of monomorphization. And monomorphization is the, as the text says, the process of turning generic code into specific code by filling in the concrete types that are used when compiled. But that's sort of abstract. So let's try to pick up a slightly more concrete example and then work from there. Let's go with new lib.
[2:34] We're going to call this one. Hmm, naming is hard. It doesn't matter, but that makes it even harder because there are no constraints. We're gonna go with example written in Norwegian. All right, let's get rid of this test.
[3:06] We don't need no test. So let's say that you have a function greater. It is generic over T. Actually, let's go even simpler. Let's say that we're going to have a function strlen. And it's going to take anything that implements ASRF str. And it's going to give you back a use size. So we're going to do as ref len.
[3:39] Real simple function here. Let me make it a little bit larger. So this is a generic function. You could just as well have written it as s is s to use size where s implements s ref stir. These two are equivalent. s ref len. And I guess we'll make these pub to make the compiler stop complaining.
[4:12] So these two are equivalent. They're not quite equivalent, but they do the same thing. And both of them are generic functions. They can take in any type that can be turned into a reference to a star, which is what this says and same as what this trait bound does. And what happens is if we write any function, let's say foo, and it calls strlen of, let's say, hello world. And then it also calls strlen of string from hello world.
[4:53] in Norwegian. That is a good, handy shortcut for picking examples. So just to see why these are different, this is giving in a type of a static str. This is giving in the type of string. Whoa. Right? So this is where we get into the point of this function is generic. It doesn't just accept a string reference.
[5:25] It accepts any type that can be turned into a string reference. So string, for example, implements as ref str. Because if you have a reference to a string, you can trivially get a reference to a str. Because the internal representation of a string is a str. Right? So here we immediately see sort of why generics are useful. It's because it enables you to call into a given function in a more flexible or ergonomic manner. And behind the scenes, what happens, and this is what the Rust book is talking about when it talks about monomorphization, is that the compiler actually generates two copies of this function.
[6:08] one for each of these types. So at compile time, what we're actually going to end up with is like a sterling ref stir, which actually takes a stir and calls a stud Len. And we're going to end up and we're going to end up with a sterling string, which takes a string and does the same thing. So this one generic definition gets turned by the compiler into these multiple non-generic implementations.
[6:48] That's the process of monomorphization. And this is sort of key to how generics work in Rust. And this process doesn't just happen for functions, they happen for types too. So imagine that you have a hash map that's generic over the key and the value. You actually get a full copy of the entire struct and all of its methods, one for each type that it is used by. Notice that it doesn't generate... copies of this for types that we didn't invoke it with.
[7:18] This is not like a generate for every possible type. It is generate for any type sort of on demand, but on demand determined at compile time. If you see code that needs this function for a given type, then generate it at that point in time. And a type would be the same. Like a hash map would only, a particular instance of the hash map type would only be generated if that type combination actually appeared somewhere in the code. This is actually also one of the reasons why it's a little bit hard to make Rust, to compile Rust code and then ship people a binary that they can use as a library.
[7:58] Because imagine that if you had this in your Rust library that you wanted to sort of distribute in binary form, think like dynamically linked libraries and stuff, it's actually fairly complicated because The contract is that Rust is supposed to generate distinct copies of this function for each type, but it might be instantiated with a type in a consumer that isn't defined where the source function is defined in the originating library. And therefore, you need the source in order to generate all those instances.
[8:31] And the reason why monomorphization is great is because you end up producing potentially much more efficient code, right? Sterling is a bit of a bad example here, but let's imagine that we had something a little more complex. Actually, a good example is HashMap. I'm not going to write out the full definition of a HashMap here. But what you end up with HashMap is because you get a copy of the type for each concrete type you use. Imagine that one instance of the HashMap has the key be a...
[9:06] a string and another instance has the key be a number, you would actually end up with the compiler, when it generates the code for each of the methods of the HashMap, it would generate, like it would sort of inline the definition of say the hashing function for each key type. So the one, the HashMap version of the code that uses string would sort of put in the code for hashing a string directly into the HashMap code, and it could optimize that code based on the fact that that type is a string.
[9:40] Similarly, for something like a number, it might be able to skip hashing altogether because it realizes, once it sort of monomorphizes all the generics, that actually the hash is just the value of the number. That might not actually be true, but you get the sense of, like, the compiler gets to see the concrete written-out code for the particular types that are used. which lets it optimize a lot better. Does this all make sense before we move on to the more complicated aspects of this? Does the general idea of generics and why monomotivation is nice make sense?
[10:28] So the downside, as someone observed in chat, is, yeah, for monomorphization, one of the downsides is that your binary ends up being larger because you need to generate a copy of the type or the function for every type that it's used with. It's not quite as bad as like just multiply by the number of types. One of the reasons is because for HashMap, for example, you might only use a subset of the methods for any given type combination. And it won't generate like... Like if you ever have a HashMap that has string as the key type, it generates the entire HashMap, like all of the methods for HashMap for the string key type.
[11:08] It will only generate the methods you actually end up calling. So that amortizes the cost a little bit. But it is true that it leads to more code in the final binary. And a sort of side effect of that is that your code can be a little less efficient in the sense that now, rather than having one function called Sterlin, that like one sequence of like assembly, like machine code, really, that the computer can jump to.
[11:40] And then it can keep those lines of machine code like in cache, which lets it execute it more, more efficiently the next time around, what you end up with instead is you have two. different functions, and some code jumps to one and some code jumps to the other, and they have to be cached separately because they're separate regions of memory, as you actually end up with a slightly worse cache efficiency for your instruction cache, which is a downside. It's also a little bit expensive in the sense that the compiler does need to generate these copies, but usually that's not too much of a cost, like actually generating these, unless you end up instantiating with a very large number of types.
[12:22] Um, Is that one of the primary reasons Rust binaries are larger than C ones? So that is slightly different. Rust binaries statically compile more stuff, which might be part of the reason. Part of it is monomorphization. Part of it is, I forget the exact details, but I think there's more stuff from the standard library that gets compiled in. And another really big one is that Rust often builds in debug symbols.
[12:54] which if you don't strip them from the binary, you end up with a binary that has very little actual machine code, but a lot of debug symbols, as you might want to try to just strip the binary. Will the compiler try to inline generated functions? Yeah, so this is one of the reasons why monomorphization is really good, is because it doesn't just inline whether it's string or str, but if you have, say, a PubFn, like... a bool then, which takes a Boolean, and it takes an f, which is a function, and it returns you an option t.
[13:42] And then let's say the implementation is something like, if b, then some f else. And this function actually just landed in the standard library, although as a method on bool. So here, if you ever ran this function with a particularly provided... closure or function, it would actually generate a copy of bool then with the code for the closure you passed in directly inline into this function. And so it could be optimized accordingly.
[14:14] So yeah, it does end up inlining. Inlining is the wrong word here. It has the option of inlining and optimizing as based on that. It doesn't have to. It's just that because it gets monomorphized to the particular type, it knows exactly what that type is, and it can choose to inline if it wishes, which is an important distinction. Big reason for larger size is standard lib.
[14:44] That's not quite true because only the parts of the standard library that you actually use end up getting put into your binary. It is true, though, that if you're using a lot of generics from the standard library, that ends up growing the size. How big of a cost is duplication of methods? Basically none. I think the actual generation of multiple functions isn't that important, but what is important is if you generate many copies of a function, you have to compile each of them into machine code, which slows down the compilation process. Wouldn't strlen string take ref string rather than just string by value?
[15:23] It could take either, actually. They will both work, which is one of the reasons why taking askRefStir is nice. How do dynamic libraries handle generics? They don't. This is one of the reasons why it's challenging to do dynamic linking of Rust libraries, or even just distributing Rust libraries in binary form. And it's something that I think in Swift, they've been trying to stabilize something like this.
[15:54] We don't quite know how to use it for Rust yet. And yeah, you can't use it for something like if you want a C dilib, like a dynamically linked library in Rust that has a bunch of like external functions, those can't be generic. All right. So now that we have an idea of what monomorphization is, I want to talk a little bit about what the actual process of dispatch here.
[16:27] So dispatch is the idea of... Actually, let me give you a slightly better example that we can work with for a little bit longer throughout the stream. So let's define our own trait. We're going to call this trait... just call it Hello, it's simple enough, or I guess let's go with the Norwegian hi. And it just has one method.
[17:00] And let's say it actually returns nothing, it just has a symbol as a single function that just lets you say hello in Norwegian. And we can imagine that we implement that trait for let's say, stir. Um, and all that's going to do is it's going to print line, uh, self oops. Um, and then we're going to do, uh, I guess let's just go with J dot.
[17:40] Hi. Ah, can't type today. So what happens behind the scenes here is that when the compiler tries to generate the code for this, it determines the type of this, then it looks at which methods are available on just the str reference type. It doesn't find one called high. And then it looks at the traits that are in scope, it finds that there is a high method on this, which is implemented for the receiver type.
[18:18] And so it ends up calling that. Seems fine. Now let's imagine that we have a sort of generic version of this, where we take something that implements high, and I guess h. And it's just going to call h.high. So this one's trickier, right? When the compiler has to generate the machine code for this, it needs to somehow call this method, but it doesn't actually know the type of H. And this is where monomorphization comes into play, right?
[18:51] That in reality, what's gonna end up being generated is a bar str, which has H, B, str. And now, dispatching this, figuring out what to call here is trivial, because we know the concrete type. So this is what's known as static dispatch. That is, at compile time, the compiler knows what the actual type is. And therefore, when it tries to call this method, it just knows that that is this method.
[19:22] And it can just jump to, like this basically becomes a call in like assembly code to call this function, which is at some known location in memory, right? Because it's just where this method is. Does that make sense for static dispatch? That actually figuring out how to compile this code becomes trivial once you can generate this method, because this method is really the same as this. And these are both trivial to figure out where the high method lives.
[20:05] So now that we've looked at this sort of static dispatch, you might wonder, well, what is the alternative? What if we don't want to generate a bunch of different copies for this? So this is where we go back to dynamically sized types. Oh, sorry, yeah, impel-hi here is just syntactic sugar for generics. This is equivalent, like I showed with Sterling before, this is is equivalent to H is high.
[20:40] These two are equivalent. Yeah, so what then is the alternative? We don't want this monomorphization, we don't want multiple copies. Or the other reason why you might imagine this is, let's say that you want to let's say you have a vector of things that implement high. In foo here, I want to have a vector of this.
[21:21] And I want to do like for h in this vector, call h.high. That's fine if they're all the same type. But what if I wanted a sort of collection or sequence or set in some way of things that are high, but I don't need them to actually be the same type. All I care about is that they implement this trait. So more concretely, imagine that I want to write bar, and I want to take anything that is a, say, slice, of like, imple high.
[22:02] Let's start start with this version, right. So for H in s, h dot high. This works fine. I can call bar with say a with something like this. works just fine, that compiles just fine. Similarly, I can do I can turn each of them into strings. That also works just fine.
[22:40] Oh, right, I didn't implement this for string. So that works just fine. But let's imagine that I want to be able to call it with like, this should really be fine. But I can't do that, right? Like, I can't create a vector of things that are different types. That's not a thing that I can make in the first place. What I really, but in this case, I don't actually care what the concrete type is.
[23:11] I don't care that these are strings. All I care about is the fact that I want them to implement the height trait. That's all that matters to me. So I should be able to create a vector of things that have this behavior without caring about the concrete type. And this is where we get into the area of dynamic dispatch and trait objects. And the book has a chapter on this too. Let me find where that one is. I've opened it in the wrong order, which was silly of me.
[23:50] Sorry about the jumping around. It is down here in the chapter here. So the book has a pretty decent chapter where it talks about the ability to treat things that are different concrete types as the same type. So another example that they use is in the case of like a GUI, you might have lots of things that are drawable, like they implement the draw trait. And you might be able to take, you might want to have like a draw function that just takes a sort of list or iterator.
[24:25] of all of the things to draw. And some of those might be buttons, some of those might be images, some of them might be text boxes, but it doesn't really matter for the draw function. All it cares about is that it gets an iterator of things that are drawable, which has a similar sort of flavor to this, right, where we want to just take a slice of things that I can call high on. And what you need is what's known as a trait object. A trait object is where you see the din keyword.
[24:58] This isn't actually gonna compile. So what I'm gonna do is sort of, this is sort of what I want, right? So, imple, remember, is a shortcut for, and this is where it'll be useful to actually write out the types, is a shortcut for this. And this sort of gives a clue to what's going on. Bar is generic over one type, which has to be either a str reference or a string. It can't be both because it's only generic over one type. And you can imagine that we have like an H2 high here, but given that we're taking a slice or let's say an iterator there is nowhere to put h2.
[25:38] There is only the one iterator, which only has items of one type. So this won't really work. In some sense, what we want to say is that each of the things is a high. It doesn't have any other concrete type that we care about. And in fact, if we write this, we get a compiler error saying, let me pull this up on a new screen. It says, trait objects without an explicit din are deprecated.
[26:10] Okay, let's get rid of the warning first. It's saying we need to put din here, so we're just going to do that. And now it says, the size for values of type din high cannot be noted compilation time. So it points to this and says, doesn't have a size noted compilation type. The trait sized is not implemented for din high. Slice and array elements must have a size type. This is an error that you might have come across before. And part of what we're going to be talking about for some of the remainder of the stream is why we get this error, what it means, what the fix is, what sized means, and sort of how this ties into dynamic dispatch and trait objects.
[26:50] Let me pause here for a second because I've just thrown a bunch of stuff at you. Let's see whether it makes sense. So it's a bunch of discussion of dark mode and light mode. So really, what we want to say is, you can think of this as sort of type erasure. We want to say that I want to take a collection of things that, and I only care about the fact that they implement this trait.
[27:26] I sort of want to take an abstract notion of this trait. All right, so the challenge that the compiler is pointing out is in this case, where are we going to even start with this? All right, I think we need to talk about the sized first. So let's go to the sized trait. So the size trait has no methods. It is a marker trait.
[27:58] That's what is in the marker module. And the description just says, types with a constant size known at compile time. Now, most types are sized. Like if you create a struct foo, it's probably sized. Most types in the standard library are sized. In fact, there are very few types that aren't sized. So few, in fact, that every trait bound you have, even if it's just like a foo T, has an implicit bound of requiring that the type is sized.
[28:32] And to see why, think about what happens when, let's just sort of comment this out for a second. Let and comment this out for a second. I just want to get actually, I guess I can do this smarter. So let's sort of go back to our very simple strlen example in the very beginning, right?
[29:05] It's gonna be generic over some S that implements asterisk str. It takes that S. And it returns uSize as ref length. So imagine that something wants to call strlen. Well, strlen takes an argument that is that s. So it has to be past a thing. Like somehow it needs to be past that argument. Well, the argument that it gets past has to take up space on the stack or has to be passed in a register, either or.
[29:41] Which sort of means that the compiler has to make sure that there's sort of code in the resulting assembly that allocates the required space on the stack for whatever this argument is. And that requires that the compiler knows how large the argument is. If s here, I guess think of the concrete implementation, so strlen str. Here, this is just a, hmm.
[30:20] And let's go with the string implementation. So string is really just a, it's sort of two numbers and a pointer, right? It's the length of the string, it's the size of the allocation, and it's a pointer to the first character in the actual string on the heap. So it's size. The compiler knows that the size of this argument is three words, three. use sizes, if you will, right.
[30:52] And so we can generate the assembly code for this function and for calling this function trivially, because it knows how much space the arguments take up. You can imagine something similar, right, where if we were generic over the return type, it would need to know how much space to actually allocate for the return type on the stack. And so even though we didn't specifically say that s is sized here, it just is basically always a requirement that the type is sized. Because if it wasn't, the compiler wouldn't know how to generate the required code for it. Right.
[31:35] All right. So why. Why then is it compiling when we're trying to use this? Well, din high is really just saying anything that implements high, like just something that generates high without giving a concrete value. Because remember, we want this to be a slice of potentially like string and stir and whatever other types might implement this trait. And those are all different sizes, right? A string is two numbers on a pointer, a str is one number on a pointer, and you can imagine that we have some type foo that is like a gigabyte large as a struct or something insane, right?
[32:16] And we implement hi for it, and that is also something that we might wanna pass in here. So this slice doesn't have a size. It's just not, like if you, a slice is really just a contiguous piece of memory, right? Where each chunk is the same size. It's an array where all of them are the same size. But if we don't know the size of them, we can't guarantee that they are the same size. If I told you, if I gave you one of these, So din high here is not sized, right?
[32:47] Because it could be any type than once high, which could be any size. And I asked you, give me the fourth element. Normally in an array, because all the elements are the same size, the fourth element is just the pointer to the start plus like three times the size of one element, right? This is a pointer arithmetic to get to the fourth element. But if they're different sizes, you can't generate that code. And this is why it's saying slice and array elements must have a size type, because otherwise, the type just doesn't make sense.
[33:23] So how can we fix this? We really want to be able to do this. It would be insane if Rust didn't give you the ability to talk about things that implement a trait as a collection. And arrays aren't the only problem here, right? Even if we took, even if we wrote, what's a good example of this? Let's say we had a strlen2 here that took a like din asref str. It has the same problem, right?
[33:57] If I try to compile this, you see it says the same thing. Let me get rid of the other message. It says, the size for values of type din sRF str cannot be known at compilation time. Sized is not implemented for din as ref. Function arguments must have a statically known size. Borrow types always have a known size. And then it tries to give you a suggestion for how to fix it. But this is sort of the key insight again, that the compiler needs to know how large the type of an argument is.
[34:31] Otherwise, it can't generate the function call code. And so this is sort of like a fundamental requirement of the compiler that these types are sized. Does that make sense so far, like why this is a problem? Can you show us implementing sized? So sized is auto-implemented for any type that can implement it.
[35:04] So if you do like struct foo with no fields, it is sized. If you add a string in there, string is sized, so foo is sized. If you add another bool, this type is now still sized. Types are always sized if they can be. The exception would be if I did something like... And in fact, even if I did foo t instead of this holds a t, it's still sized because remember that there's an implicit requirement for every trait bound that it is sized.
[35:38] So there's sort of an implicit t sized here. And so that means the T is sized. So all the fields are sized. So therefore foo T is sized for any T. So you never implement sized yourself. It is only ever used as an auto trade. The issue is not stack size.
[36:12] The issue is not that it might not fit on the stack. It's that in order to call a function, right, just at the machine code layer or think of it as the assembly layer, right, in order to call a function you need to know when you call that function how much space do you allocate for the like stack variables of that function. We might include some of its arguments or on the caller side when you have to allocate the space for the return value, how large should that space be? Fundamentally, that just requires that you know how large the space is, because you can't generate the machine code for making that stack.
[36:49] There are like sneaky ways you could do this, but basically, the compiler, in order to generate efficient code, has to know the size of these things. Let's see. What things aren't sized? So we've talked about bear traits. So this is if I write pubfn foo, and I just say that I take a high.
[37:27] High here is a trait, and lots of things implement that trait, and they might all be different sizes. So this doesn't have a defined size. If I say impl here, right, impl is a shortcut for H. Hi. So this ADH is sized because we get a copy of foo for every concrete type. And for each of those copies, the size of the type is known. So if we use static dispatch here for monomorphization, this is fine.
[37:59] But if we just try to take like the trait itself, saying basically this function takes anything that implements the trait, this won't work because this is not sized. And this is equivalent to writing din hi. Like this is not sized. We'll talk in a second about how you make something like this sized. Um, the other example is something like, um, uh, if we go back to my, my struct foo, uh, if you try to have it hold a stir, uh, stir is not sized, um, because a string can be any size sort of, if you think about not the pointer to the string, but the string itself can be any size, uh, the same with like, um, This, just like a slice without a reference, is also not sized because you don't know how many elements there are.
[38:51] So it doesn't have a well-defined size. Those are the two best examples I know of, of things that aren't sized. And then anything that, in turn, contains those types. There's a lot of discussion in chat trying to explain the things that I'm about to explain on how we fix this and why you need references and stuff. I will get to it, I promise.
[39:28] Great. So I think roughly where we've gotten to so far makes sense, it seems like. So the question now becomes, how can we resolve the situation? We want to be able to take a, for our Sterling 2 here, let's call it Sterling Din maybe. We want to be able to have a method like this that doesn't get monomorphized. But this isn't sized, so what do we do? The trick here is to make this be a type that is always sized.
[40:05] And the way that we do that is by indirecting it through some type that is itself sized for any inner type. An example of this is a reference. So a reference is always the same size, it's just the size of a pointer, or in some cases two pointers, we'll get to that in a second. This does have a size. The compiler always knows how large one of these are, no matter what the type that follows is. Because this is just a pointer.
[40:40] The same would be if you have a box. right? A box, also just a pointer to the heap. And so once we do this, the size of this argument is now known, and we're fine. And this is in fact how you take something, take a trait itself without monomorphizing, is you place it behind some kind of pointer type. Like a reference, like a box, like an arc.
[41:13] The way this works in practice is that if you look at the definition of box, so it has magic in it, right? It's not magic, but it has a bunch of stuff inside of it. Basically, it just has a pointer. It's not quite true, but close enough. Box actually has this definition on it. And the question mark here means does not have to be. So it's basically opting out of the auto bound that gets added of everything has to be sized, saying for box, the T does not have to be sized.
[41:50] And that's why you can create a box of something that itself is not sized. And the reason this works is that when you create the box initially, you make an allocation that's the size of whatever you're going to put inside of the box. So let me make a main here that's going to exemplify this. At some point, I have to do box new of, say, string from hello.
[42:25] Right? And then I can say that now this is going to be a din as ref str. This should say x. And this should say str. And then I can call strlen din with y. So at some point when I created the box, I had to give it something with a concrete type. And at that point, it allocated on the heap space for that type.
[42:57] But the box is still of a known size because it's just the pointer. When I turn it into a box for this, it's still just a pointer conceptually. even though the thing it points to might have an arbitrary size. But the actual argument that we pass to this function does have a size, and therefore we can generate the relevant code. Does it make sense why indirection through a type like this where the indirection type size is known? Does that make sense?
[43:37] We'll talk about combination of traits too. Let's see. I promise we'll get to multiple traits. Can't you just put BoxedInAsteroidStir directly on X? Yeah, so you can do this too. AsteroidStir. That's also fine. But even so, you still had to provide a concrete type to Box New that was sized.
[44:16] When should we use box over references? Like when do you choose this over this? There's no hard and fast rule there. In general, the advantage of box is that it's static. So you can keep using it even after the stack frame of the caller goes away. So it's the same as when do you choose box over references normally. Can I also then give the function a reference to the stack? Yeah, exactly.
[44:47] So you can also do, let me do that down here. So I can totally do, and then Sterlendyn, why? Right. So this, let's say I have a din2 that takes this, and this can call din2.
[45:25] Why is this complaining? It's because box has an asterisk method too. That's why the double asterisk is needed. Yeah, so you see, I can do the same for something that's on the stack. I can create a sort of go through a pointer in direction here and then pass it to something that takes a referenced in.
[45:59] And in fact, I think I can even do this. Yeah, that's fine. It's not terribly important why that doesn't work. So what we just constructed is known as a TraitObject. It is an object that only has the property that it represents a trait. So this is what TraitObjects are. They are things that only behave as some underlying trait.
[46:35] This is a TraitObject, and this is a TraitObject. It doesn't matter what the wrapping type is. Box is kind of a pointer type. Yep, box is a pointer type. Can I convert a trait object to its original concrete type? I'm going to go with no, but technically yes, sometimes. But in general, no. You can think of it as, this is essentially type erasure.
[47:08] You can technically go back through like unsafe transmutes and stuff, but in general the moment you turn it into a trait object You erase the knowledge about what type it used to be But yeah, there's like some magic around unsafe and some magic around the any trait that you can use. But in general, you should ignore that. Also note that when you do this, you only retain the ability to use this trait. You erase all other knowledge of what the concrete type was.
[47:39] So the only thing you can do on a boxed in ASRF stir is call ASRF on it, nothing else. Same thing here. And we'll get into why in a second. All right. So this raises an interesting question. Let's take the example, let's make this the two and this the one, and just swap these around so this still compiles. Let's now think about what actually happens when the compiler has to generate the machine code for this function.
[48:15] At some point it has to actually do the compilation and produce assembly code that can in turn be turned into runnable machine code. So S here is some type that implements Sref. In fact, let's go back to our high trait. That's going to be a little bit nicer. So let's go back to here and let's say that I want a sayHi which takes a dinHi, returns nothing, and just calls Hi Right? So this is going to be, this takes a trait object for the Hi trait But when the compiler generates the code here, it doesn't know what type s is Right?
[49:01] It's just a trait object. It's really just a pointer. So how does it call the high method? Remember, in the generic case, static H. In this case, we actually get a copy of this for each concrete type.
[49:37] So really, this turns into this. And for this concrete implementation, generating the machine code is trivial, because this is really just like an assembly call to whatever it is, to this line, to line 6. It's not actually line, it's memory locations in the binary, but you get the idea, right? That the compiler knows statically at compile time where to go here.
[50:10] For the dynamic case, though, what do we call? We don't know that this is a str or a string, right? So we don't know whether to generate the address of this, the address of this, or the address of something else entirely. So what machine code does this turn into? Well, this is where we get into dynamic dispatch and V tables or virtual dispatch tables. So the trick to constructing a trait object is that it's actually not quite true that the reference of the box is just one pointer wide.
[50:48] It actually carries a little bit of extra information about the type that is pointed to. So here, let's go back to the, back to the the Rust book. So the Rust book has a chapter on dynamically sized types and the size trait. This is under the advanced type chapter. And what it's talking about is, in fact, it doesn't even talk about as much as we wanted to talk about. Here.
[51:22] Let's use the Rust reference instead. So the Rust reference on dynamically sized types says, most types have a fixed size that is known as compile time and implement the trait sized, like we've talked about. A type with a size that is known only at runtime is called a dynamically sized type, or informally an unsized type. And this is the slices and trait objects are two examples of dynamically sized types. The reason why this is only known at runtime is, at compile time, we don't know what type this is gonna be. It's only at runtime that we'll know.
[51:54] And we can, to make this a little bit more concrete, imagine I have a main function where if rand, I don't have a random number, random is four. If random is four, then say hi of this, Otherwise, say hi of string from world. Right?
[52:30] And let's imagine that random was more random than 4. You don't know until runtime. Let's say this was read from the user. At compile time, you don't know which actual type is going to be used here. It's only determined at runtime by some input that can't be predicted at compile time. Right? So that's why this is determined at runtime. And it says, pointer types to dynamically sized types are sized but have twice the size of pointers to size types.
[53:09] So pointers to trait objects also store a pointer to a V table. And this is where we get into what is a V table. Well, when you have a trait object, something like at din pi, what actually gets stored in the reference is one, a pointer to the actual concrete implementing. implementing type, and two, a pointer to a V table for the referenced trait.
[53:48] So then what is a V table? So a V table or a virtual dispatch table is a little data structure that has pointers to each of the methods for the trait for the type. So in the concrete case of the high trait, so let's say we have a din high, the V table is going to be sort of you can think of it as a high V table struct that only has one member, which is high, which is a pointer to an Fn, an Fn actually, that itself takes a pointer to whatever the T is.
[54:45] So basically, a different V table ends up being constructed for each concrete type turned into a trait object. So when we start out with, let's say that we have a stir, and we want to go to a din high, what actually gets constructed is a let's say we have a um Well, number one becomes a pointer to the str.
[55:16] And number two becomes a high Vtable, where high is str as high, high, and a pointer to that. When you make this conversion, the compiler knows that it has to construct this Vtable, and it sticks the address of that Vtable inside of that reference.
[55:48] So this reference contains two things, the pointer to the actual type and the pointer to the Vtable that the compiler generated during this particular conversion. So there'll be one such Vtable for each type that gets turned into a TraitObject. And so now when the compiler tries to generate this code, what it actually generates is like s.VTable.High s.Pointer.
[56:23] And so if someone passed in, say, a string instead, it would have a different Vtable. So the s.Vtable would be a different pointer. So in this case, this would be where is str high? Like line 6, right? So this would be a pointer to line 6. But if we instead went, I'll stop for questions in a second. If this instead went from a string to a dyn high, It would be a pointer to the string and string as high, which is this method up here on line 12.
[57:06] So in other words, this code that gets generated will work regardless of which type is passed in because we indirect through the V table and each type has its own distinct V table. All right, that was a lot to throw at you at once, but hopefully it wasn't too bad. Let's see.
[57:45] Are the V tables themselves statically built at compile time, or are they also allocated dynamically? The V tables are... The V tables are built at compile time, they're built statically. And so in general, the second part of the... So this is what's known as a fat pointer or wide pointer, because it has two pointers in it, not just one. So anytime you see this, it's actually a wide pointer. And in general, the second pointer in there will always be known statically, because it's determined by the original construction.
[58:23] of the trait object. The reason I say generally is because you technically can construct it on the fly. There's nothing in the calling here that requires that it was known statically. So you could imagine manually constructing a vtable. And this is used, we'll actually talk about that a little bit later. Refster also contains the length of the string slice.
[58:56] Yes. So in general, this will actually be this. So it's not a pointer to the actual string. It's actually a pointer to the str reference, which itself holds the length. Can we debug print the Vtable struct somehow? I don't know of a way to get the compiler to print its Vtable struct, but it's basically just this.
[59:33] It just, there's a member for each method of the corresponding trait that this is a trait object for, where each member is... Each member is a corresponding method, and the value is the pointer to the implementation of that method for the concrete type. Then why are trait functions that don't take self not object safe? Couldn't the compiler just generate an fn mute self that doesn't use self?
[1:00:08] We'll talk about that in a second. Does it construct a new V table every time we create an instance? No, the V table is generally statically constructed for the type. It doesn't get constructed dynamically. Are identical V tables detected? No, there's no deduplication of these. And in fact, they are guaranteed to not be duplicates.
[1:00:43] If you implement a trait for two different types, then the implementations, even if they contain the same code, are still distinct locations in the source code and in the resulting binary, and so would have different addresses. Trait objects of more than one trait we'll get to in a second. So box din is a thin pointer that points to a wide pointer that points to the object. No, if you have a box din height, that box itself is a wide pointer.
[1:01:22] So box is a little bit of a special type. Actually, it's not that special. It's just that box internally contains a mute dhinhi. And the Rust compiler knows for references and pointers that if they are trait objects, they're actually width 2. So box isn't special, but pointer types are. So box.dynhi is itself wide. You don't end up with an extra indirection. Yeah, we'll talk about nightly APIs for trait objects too.
[1:02:13] All right, so I think we're now at a point where that roughly makes sense. So there are a couple of reasons why trait objects are a little bit more constrained than being fully generic. So, for example, let's imagine that you wanted to have a... hubfn baz that took an s that is din, let's say, hi plus sref stir.
[1:02:58] And we're going to do s.hi. And then we're also going to say, let S is S dot S ref. And then we're going to do S dot high again, because we know that strings themselves implement high. I guess maybe that's confusing. Maybe I should just do len. The compiler here said, oh, it's ambiguous. All right, let's get rid of the ambiguity. It's not really relevant to the discussion.
[1:03:33] It still won't let me do it, why not? Do I have to do this maybe for it to not be ambiguous? No, all right, I'm just gonna, let's pretend that the syntax worked for a second here. So basically I want to say that I want a trait object of two different traits. This won't actually compile and ignoring the parsing error for a second, there's actually a bigger reason why this won't work, which is, In order for this to work, we need to know both where the high method is and where the asref method is.
[1:04:18] But those are contained in two different vtables. One is the vtable for high for the concrete type, and one is the vtable for asref for the concrete type. And so what we'd actually need is not just a two-wide pointer, but a three-wide pointer. A pointer to the data, a pointer to the vtable for high. and a pointer to the V table for ASRF. And that's possible. There's nothing that's sort of inherently impossible by that, but it would mean that as you add more traits, the size of this reference just keeps on growing.
[1:04:55] And that's probably not what you intended. And you might go, well, can't the compiler just generate a V table for the combination and then pass that in? That is something that in theory it could do. The Rust compiler doesn't currently do this. I don't know of a proposal. to do it. Part of the reason is because you can get around this by saying pub trait high azref and it requires that the type is both high and azref str with no methods of its own.
[1:05:28] And now I can do this. Right? Because now there's only one Vtable, and that Vtable is high ASRF, and the compiler knows when it has to generate the Vtable for this trait, that includes all the methods from both of these traits. And so this Vtable is going to be larger because it is going to have both the high method and the ASRF method. And so I think part of the reason this hasn't landed in Rust itself is because you can opt into it yourself. And by not automatically turning the plus into a larger V table, you basically tell the developer that this might not have been what you meant, but if it is, you can do this thing instead.
[1:06:12] I agree the compiler error here probably been better, right? Some in Esteban Cooper. That maybe we could sort of inform... people that they can generate their own trade here. I think it's someone wrote I think it's I plus s ref.
[1:06:52] Stir, let's see if that's true. Yeah. Okay. So, so that is the, the, the way to get the right compiler error, which is only auto traits can be used as additional traits in a trait object. Whereas here you have an example of two different traits that are, neither of them are auto traits. We'll talk about that in a second. And here it does actually give the suggestion we talked about, right? Consider creating a new trait with all of these as super traits and using that trait here instead. And it also points out that auto traits like send and sync are fine.
[1:07:27] And basically the idea here is that for marker traits, like if I want to say high plus send, send doesn't have any methods. So it's fine for the V table to be empty. And therefore we don't need to store that additional part of the V table because there aren't any methods in it. So that's why it's okay to have additional traits with no methods. I don't think you can use your own. Like if I did a Fuchs trait and I said this plus Fuchs, I don't think that'll work.
[1:08:00] But there's been some proposal of having a marker annotation to declare a trait as never having methods. But that's not something we currently have. So at least for the time being, this is the way that you should do it. Great.
[1:08:34] All right. So that is how this works with combinations of traits. But that's not the only example where trait objects are a little bit limited. So the other one is, let's imagine that for high, we added a, actually, let's start with saying that we added an associated type. Let's call it name. And we don't actually use it for anything, we just add one. The code already doesn't compile. Why doesn't it compile?
[1:09:05] Well, the value of the associated... Oh, that's the implementation. Let me do that. So this is going to be type name equals unit. Just going to use that for both of them because we don't actually care about the type. Yeah, so here it says the value of the associated type name from the trite high must be specified. So it says here where we take a din high, we actually need to specify the associated type.
[1:09:39] We can't just say we take any high regardless of what its associated type is. And the reason here is because that information can't be captured in the V table because this is a type. It doesn't have an address in the binary. It doesn't have anything we could stick in the V table. And therefore, this won't work with a trait object directly. Instead, what you would have to say is I take a high where name. is this. And I think we need to do the same down here.
[1:10:15] And then that works. Because now we have a V table specifically for anything that implements high where the associated type is name. So that's fine. Let's undo this because it's not a very interesting change. The other, perhaps more interesting case is, let's say that we want a... What are we going to call it? We're going to call it, like, weird. We're going to have a weird function that does nothing.
[1:10:48] No one needs to implement it. And you see that this also does not compile. Error in cargo check. Let's make this a little bit smaller so that hopefully it's a little easier to understand. Hopefully it's still readable. Ooh, that's very verbose. Let me comment out the combination trait bit just to make the errors a little nicer. Alright, so this says the trait high cannot be made into an object.
[1:11:24] So when we say din high, basically it's telling us that the high trait is not object safe. That is, it cannot be turned into a trait object. And it says for a trait to be object safe, it needs to allow building a V table to allow the call to be resolvable dynamically. So this is what we've been talking around through so far. And in particular, here it says the trait cannot be made into an object because the associated function weird has no self parameter. It doesn't really talk about why that's necessary though. But let's try to work through it.
[1:11:56] So again, let's say that down here in our sayHi, right? We now try to call s.weird. So imagine what would the compiler do if we wrote this code? Well, we can't really write this code, right? Because weird doesn't take self. It doesn't take a pointer to anything. And we can't just like randomly construct a pointer to it because that would mean that we need to have a valid instance to it to have a pointer to it.
[1:12:28] So this is really just saying like, then hi, like colon colon weird. which I don't have to tell you seems weird because which type are we calling weird on here? There is no, like nothing here specifies which actual weird implementation we want. In this particular case, because it provides a default, you might think it's not a problem. Well, what if there was like an implementation of weird for string?
[1:12:58] that was different from the one on the trait, which is allowed, right? You can override a default implementation. Well, how would this know whether to call the one for str or the one default for the trait or some entirely different one? It can't be in the V table because there is no S here, right? The weird method doesn't take itself. It's not associated with any given instance of any type. So this just doesn't work. It's not a meaningful thing to say.
[1:13:32] But what if you really wanted this? Like you wanted the weird function to exist, but you're like, I don't care about calling this through a trait object. I only care about the high thing. through a trait object. So I want high to be trait object safe, but if you have a trait object high, I'm fine if you can't call it weird. So you can do this. this.
[1:14:09] And let me go back down here, have the speed in high again, s dot a. So. What we're saying here is that the weird function requires that self, that is the type that implements the trait, is sized. And we remember that traits aren't sized. If you just have like din high, that's not sized. It's only sized if it's behind a pointer type.
[1:14:43] So this is basically a way to opt out of the V table is the way that you can think about it. It's saying this function shouldn't be placed in the V table and crucially shouldn't be callable through a trait object. What this means is in here, let me get rid of the static versions because they're just in the way. What this means is now the code compiles just fine. I can call hi, I can make a trade object for it. But if in here, in fact, I can go even further and say, let's say that this did have a self, but I wanted to opt out.
[1:15:22] then this still compiles, I can still make a trait object for it. But let's say that I try to call weird in here. the compiler is gonna tell me the weird method cannot be invoked on a trait object because the method has a size requirement. And so this is the way to opt out for any given function from having it be included in order to make sure that the trait remains object safe. You can also say that the entire trait should not be possible to turn into a trait object by saying where self is sized.
[1:16:01] So if you do this, you're basically disallowing using this trait as a trait object. It's rare that you see this in practice. Usually the trait will, like the trait just isn't object safe because of the methods in it. Opting into disallowing trait objects is rare. Sometimes people do it for... backwards compatibility reasons. Like if you know that you might add non-object safe methods later, you might add this proactively, but it's pretty rare.
[1:16:36] All right, do the restrictions so far make sense? Does the associated type problem also occur with static dispatch? No, it doesn't. And the reason is with static dispatch, because it gets monomorphized, you actually know the concrete type for any given function implementation. s colon colon weird could be possible.
[1:17:10] So this is back when we had the fn weird, right? And let's say we also had an override here. And now let's say you wanted to be able to like, let's say we added like special syntax like this saying for the type of s called the weird method. you could imagine that weird got included in the vtable for the trait object, but it knows to not call it with a self argument. The challenge here is that this is sort of odd.
[1:17:45] If you require an instance of the type anyway in order to call it, then why doesn't it just take self? The traditional example of this is that weird is actually called new or something like new, right? Where it doesn't, if you already have an instance of the type, you wouldn't need to call the method in the first place. It would just take self. So I agree like something like this maybe could be possible. I think in practice, it's just not usually very useful.
[1:18:19] And that's why it hasn't been a priority. There might be a deeper reason why it's not added to. I'm not sure. um um does where self colon sized also disallow implementing the trade for concrete dsts um You know, that's a good question. So the question is basically, if you have where self is sized, can I implement high for box din as ref stir?
[1:18:58] for example. I believe I can. The reason I say this should be possible is because, yeah, this now won't work because it can't be a trait object, but you can still have this implementation, I believe. Why does this? Oh, right, because it's a box. So we need to have the double sref. This is fine because this is not a dynamically sized type.
[1:19:35] Again, when you wrap it behind a pointer, it now has a size. It's not dynamically sized. So it doesn't prevent that, even if you have self-sized on the trait. The associated type restriction feels weird because the point of associated types is that only one exists for any given concrete type. So shouldn't the V table know what the associated type should be? Like, it can't have a pointer to the type, but the implementation of the trait should know what the type is when it's compiled.
[1:20:07] Yeah, so the problem is that the type is erased. All that remains is the V table. And so you can't tell from the V table what the concrete type used to be. There is an exception to this, which is the any trait. So the any trait has a method that returns... turns a descriptor of the type of the concrete type that it used to be. If you didn't follow that, that's fine. Ignore it. But basically, there are some ways to sort of finagle around this. But basically, trait objects are type erased.
[1:20:38] Like you don't get to keep information about the type it used to be. Oh, you meant type such as str or u8. No, you can't do that. Self has to be sized when you have where self is sized. There's one other restriction that you get with TraitObjects, which is that the methods cannot be generic. And for this, rather than sort of keep working on our weird high trait, I'm actually gonna go to the standard library and look at the fromIterator trait.
[1:21:16] So the fromIterator trait is something that's implemented by Vec, for example. This is how collect works, is that Vec implements fromIterator. And when you have, well, So if we look at iterator collect, I guess is the best way to do it. Collect on an iterator requires that the thing that you collect into implements from iterator. So that's why you can have an iterator and collect into a vec, it's because vec implements from iterator. The from iterator trait is a little weird though. The A type of the trait is the type of the items of the iterator.
[1:21:55] but you also see that the from iterator type itself takes a T. And the T here is the type of the iterator, right? Cause it has to be vec, for example. It doesn't care what the iterator is. It can be, it can, you can construct a vec from any type of iterator, as long as the, well, you can create a vec T from any iterator where the item is T. This arguably should be called I for iter, but it's not terribly important. Here, where a is the sort of thing that you'll end up with a vec of.
[1:22:30] So if this a was, say, bool, you would end up with a vec of bools. And the t is the type of the iterator, which might be something like, I don't know, like a HashMap Intuator or whatever that type ends up being. This poses a problem for a Trait object, though. Let's imagine that we try to write code against this. So I'm going to erase this for a second. In fact, I'm going to write a new one. erase all of the remainder of this file. Then I'm going to have like, what are we going to do here, let's do collect.
[1:23:09] Standard iter from iterator, we're going to take a from iterator of bool. And we're going to return a vec of. And I'm going to do s dot collect. Ooh, what did I do? I did something weird, didn't I? Great. So this seems like it should be fine, right? I take anything that can, I take.
[1:23:42] Well, actually, this is weird for a number of reasons. Maybe fromMeterator is a bad example here, because it doesn't take self either. So it actually requires self to be sized anyway. Extend is a better one. Let me dig up extend here. Great. So we're going to use extend instead. and it's going to have to take a mutant. And so we're going to do that mute v is back new, then we're going to do v dot extend.
[1:24:18] Actually, we're not even gonna do that we're going to take this is going to be the V, we're going to do v dot extend, and we're going to give it just it are once true. So we're going to just extend it with a Extend with a single bool, add true. So we take in anything that can be extended with an iterator of bools. And then we try to extend it with an iterator that yields a single bool.
[1:24:49] So we're just gonna add true, we're gonna append true to whatever thing we get. And here too, it tells us the trait extend cannot be made into an object because extend is not object safe. And if we look at extend, that doesn't immediately make sense from what we've seen so far. Right? So again, it's generic over the type of the items of the iterator. That's fine. Extend takes self. So we do have something we can stick into the V table. And given an instance, we sort of know how to call this method. But again, notice that it's generic over the type of the iterator.
[1:25:23] And this is where it gets really weird. you can imagine the like inside of vec, right, there's going to be imple t, extend t for vec t. And it's going to have this implementation. I'm going to go go ahead and call this I because I think it's more helpful. And who knows what's going to be in here, right?
[1:25:58] Yes, just to get rid of that warning. Uh, I'm going to do this. Um, I guess be a little bit more helpful. My vec. Like this implementation is going to exist somewhere in the standard library, right? Except just for vec instead. But this method is generic. So we know from the monomorphization discussion that actually at compile time, we don't end up with a single extend.
[1:26:35] We end up with multiple copies of this method. Right? We end up with like an extend rule that takes... Now, an extend, I guess, HashMapIntoIter, which takes a standard collection HashMapIntoIterator. Right? And in fact, even more than that, we're actually going to end up with, because the whole impl is generic, we're actually going to have this.
[1:27:13] That is the actual method that gets implemented. or get sort of generated by the compiler, assuming that someone tries to extend using a HashMap iterator of bools. There is no one extend. There is one for every combination of iterator and item types. So what gets put in the V table? We've nailed down that we want to extend bool.
[1:27:44] So that's good, right? So there's only, we don't have to consider the T up here because we've already chosen that T. But for extend itself, we really, in the V table, really needs to have a pointer to extending for this iterator type over bool. but that's not expressed in the type of the function. And we don't even have a way to express it. Right, you could just sort of imagine like where, like these implementation of extend is standard iter one spool or something super weird like that.
[1:28:26] But the way that it's written, nothing here says that we want the Vtable to point to the extend implementation for a standard iter once. And therein lies the problem. When the compiler tries to generate this code, there is no pointer to the appropriate implementation of extend. Therefore, the V table can't be generated. You can't generate a V table for dinExtend because it would have an infinite number of entries, one for each possible implementation of extend.
[1:29:02] And so therefore, the answer is just dinExtend cannot exist. You cannot create a trait object for extend. All right, does that make sense? That's a somewhat intricate explanation, but hopefully it all sort of ties together here. Um, could Rossi add a monomorphized version of extend extend for each T it's called with to each type that implements extend that's tempting, but it's not always possible, right?
[1:29:36] So imagine that you're compiling this code, but, um, I mean, even just for the standard library, right? Like the standard library has a bunch of uses of extend, but in crates that depend on that crate, they might call extend with even more types. So the size of the V table, like when you compile the bottom most crate, if you will, like the standard library, essentially, that would mean that the V tables for din extend in the standard library is different than the V table for din extend in crates.
[1:30:12] other crates further up because there are more possible iterator implementations that you might want to use. And so you now would end up with lots of different vtable implementations or lots of different vtables for dinExtend. And that's like it would be a combinatorial explosion kind of problem. And it would also mean that you can't pass a dinExtend from the standard library to a thing that takes dinExtend in a crate further up because their vtable types are different. All right.
[1:30:54] So this is the reason why you can't have... In order for a trait to be object safe, it needs to... not have generic methods. It needs to, all of its methods need to have a receiver that includes self. And there's another requirement, which is that the trait can't have a type that returns self. So if we backtrack a little here and say clone, and we wanna take a thing that is didn't clone, and we're just gonna, call clone because it's the only thing we can do with a din clone.
[1:31:37] Right? If you have a din clone, you can literally only do the things that the trait lets you do, and the only thing clone lets you do is clone. So this says the trait clone cannot be made into an object. This is now an error that we've seen a decent amount. The reason why you can't do this is because the clone trait, right, has a FN clone that takes self and returns self. Alright, so let's say I say let x is v.clone. What's the size of x? Didn't clone is just any type that is clonable.
[1:32:16] And it's supposed to return self, like not the reference. So it's not supposed to return a reference DynClone. It's supposed to return self given a reference. So that sort of means that it should return DynClone because that's what self is here. Because we've erased the concrete type. But DynClone isn't sized. So it would mean that the return value of this method isn't sized. And the return type of a... function must be sized for us to generate code for it.
[1:32:49] Therefore, this can't work. So you can't have methods that return self for a trait to be object safe. And that's why you can't do clone. Now, there are some cases where you have a trait where, as we talked about with high, you might have some methods that are object-safe and are still useful on their own, but you have a bunch of other methods that would make the trait non-object-safe, but you want to include them for types that aren't going through a trait object, just because it's convenient.
[1:33:23] And in fact, a good example of this is if we look at the iterator trait. So the iterator trait... right has the associated type item that's fine it has next and next is object safe but it also has a bunch of methods like chain which is generic it has enumerate which returns self it has By ref, which returns mute self.
[1:33:56] It has collect, which depends on from iterator, which we already know isn't object safe. So how can iterator be object safe? Because it is. If I say it here, and I say I want to take a din iterator where item is bool, we collect. Oops, iterator. Well, I can't call collect because this method cannot be invoked on a TraitorObject.
[1:34:30] But I can call next. I'm allowed to call next on this. Mute, otherwise it doesn't work. That works fine. And the way that the iterator trait has achieved this is that if you look real carefully, you'll see that, if I actually go to the source of the iterator trait, you should see this, you just find here.
[1:35:03] So count, for example, which consumes self, right? So it's not allowed to go behind a reference, which would make it sized, has where self is sized. If you scroll down to last, which is the same, self is sized. If we look to chain, you see the chain, which is generic, so normally would make the trait non-object safe, has where self is sized. And the reason for this is you can basically, this is the same thing we did for the weird function, right? You can use the where self is sized bound to say ignore this function for the purposes of using this trait as a trait object.
[1:35:41] Basically, don't try to put it into the V table. What that means is if someone has a trait object, they can't call the method. But if they don't have a trait object, if they actually have like a vec intuitor or like they have the concrete type, then they can call this method. And so this is a way to have a trait that has some methods that are nice to have, but wouldn't be object safe without making the whole trait object not object safe. Um, can the receiver be anything that includes self or does it have to be ref self or mute self?
[1:36:16] Um, so the rules for this are actually, uh, where do I have this? I have it open somewhere. Give me a second. Here. So this is from the Rust language reference on object safety. And in fact, by now we've covered most of these things. All the super traits must also be object safe, right? Because we construct a V table from the union of all the super traits. Size would not be a super trait.
[1:36:47] So that is, if we require self colon sized, it's not object safe. Must not have any associated constants. This again is because. you don't have anywhere to put the constants. Theory, maybe you could put them in the V table, but now the V table becomes really large. And also the values in the V tables are no longer all like function pointers. They might be arbitrarily sized things. All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable.
[1:37:19] So dispatchable functions require that they don't have type parameters, so they're not generic. They have to be a method that does not use the self type, right? The concrete type, except in the type of the receiver. So this is we can't have something that returns self, for example. It can't have a receiver with anything but the following types, right? So it can be a reference to self, it can be a mutable reference to self, it can be a box self, RC self. ArcSelf or PinSelf, PinToSelf rather. So anything that's behind a pointer, basically anything that can take, anything that can turn something that's not sized into something that is sized.
[1:37:55] And you can see that explicitly excludes where self is sized bounds so that you can have an object safe trait even if some of the methods aren't object safe. This is the non-dispatchable functions. Um, should library writers always consider adding where self is sized to non-objective methods, just in case someone downstream wants to use it as a trait object? I think yes. Um, It depends a little bit on whether your trait is even usable.
[1:38:28] So if your trait isn't usable as a trait object, like think of clone, right? Then sure, you could add where self is sized to the clone method so that people could create a trait object clone, but they wouldn't even be able to call the main function of that trait. So it's probably not worthwhile. But I do think that in general, if you have a trait where it is useful, even if you... could only call the ObjectAve methods, then it might make sense to opt out for the other ones so that the trait overall is ObjectAve.
[1:39:14] Did iterator last have the sized restriction? I think iterator last does. Um, the reason why last, uh, has where self is sized, you can't see it here. It gets hidden by rust doc, um, is because it's receiver. It doesn't go behind a reference. It consumes self, uh, which means that it takes self, um, and self is a din iterator, which is not sized and function arguments must be sized.
[1:39:47] Therefore last can't be called through a trade object. There's one more thing I haven't told you. Well, there are many things I haven't told you, but there's at least one when it comes to trait objects, which is that there's a little bit of a secret with trait objects. So let us say that I have pub trait. Actually, let's do this. This is a, drop is actually object safe.
[1:40:19] You might think that it's weird. Like if all you can do with an object is drop it, then is it really that interesting? It turns out this is useful in a couple of situations. Like I know Crossbeam does this, for example, where you want to do garbage collection, but you don't want to drop objects immediately. You want to like stick them in like a linked list or something and then periodically go and collect all the garbage. Because you want to store lots of potentially different things in one type, you need TraitObjects. And so it just stores mute in drops, or I think technically boxed in drops, but same effect.
[1:40:56] You can't actually do anything with this. But here, when v goes out of scope, dropDrop is called through the btable. This should make you go, wait a second, because let's go with our sayHi. We take the dinAsRef.stir. Or actually, let's even go with boxed.
[1:41:30] It's better. What happens when s goes out of scope? Think about this for a second. We get a box, so we have a memory allocation on the heap. We might use that in here, might call s.asref, which could be high, whatever. But then we drop s when this function returns. But when we drop a box, we have to free the memory. But this is a trait object, so the only method it has is asref.
[1:42:06] The answer to this is every Vtable includes drop. You can sort of think of this as like an implicit drop here, but in practice, the Vtable for any TraitObject includes a pointer to the drop function for the concrete type, because it's just necessary. It also technically includes a little bit of extra information. It includes the size and alignment of the concrete type. The reason those are in there is because for something like a box where you have to deallocate the memory, that information is necessary to pass to the allocator to do the deallocation.
[1:42:44] And so every trait object includes the V or the V table for every trait object includes the methods for the trait plus drop plus size plus alignment. Normally, you don't have to think about this, but it's just worth knowing while we're on the topic. To shift gears a little bit, so far we've only really talked about trait objects, but there are other types that aren't sized. So for example, we know that din trait is not sized, but u8 is also not sized, and str is not sized.
[1:43:20] This one gets turned, when you place it behind a reference or a pointer, gets turned into a tuple of a pointer to the data and a pointer to the vtable. This one, if you make it sized or put it beyond a pointer, also becomes a wide pointer, where one is a pointer to the data, but the other is just a u-size, which is the length of the slice. And same thing for str, as a pointer to the data and a u-size of the length.
[1:43:57] So this is why, if you try to write a function foo that takes a u8, the compiler is going to yell at you and say that the size for the value of type U8 is not known. Because U8 this is just saying an arbitrarily long list of U8s, which is not sized. Therefore we can't call the function with it as the argument. Same as if you try to return just a straight up U8 sequence, right? If I had a bar, which returned a U8.
[1:44:33] Um, it also complains. Oh, uh, is it even going to let me do that? There we go. I constructed the type. So here it says the same thing. The size for the value of type U8 cannot be known, and the return type of a function must have a statically known size. So this is the same problem. And here too, the way that we go from something that isn't sized to something that is sized is we place it behind a type that can sort of mask the uncisedness, which you do with a reference, or you can do it with box.
[1:45:14] So you can also do box of this. I think I'm allowed to do this. Great. So this is fine because it's now sized. The size of it is a pointer that is wide, where one part is the data and the other size is the length. Um, and the compiler then knows that when you access, uh, this type, it knows to sort of deconstruct the pointer to get the length.
[1:45:51] Um, same with something like box or, or raw pointers for that matter. And same for string. So these are a little bit magical. There's been some work on trying to standardize this. So currently the sort of dynamically sized types are a little bit special in the compiler because you need to know whether the pointer is sort of wide or not. So it's fairly hard to sort of deal with unsized types yourself. Like if you wanted to implement box yourself and take a type that wasn't sized, It's possible.
[1:46:27] It gets pretty annoying once you get into casting and allowing trait objects and stuff. But there was recently an RFC that landed. RFC number 2580. which talks about adding a generic API for manipulating the metadata of fat pointers. So this lets you do things like say what the type of the second part of the fat pointer is. Right. So in the case of in fact, we can scroll down here a little and look at a DIN trait now becomes a pointy where the metadata is DIN metadata.
[1:47:09] And we're DIN metadata. is a pointer to a Vtable that represents all the information such as type size, type alignment, a pointer to drop and place, and a pointer to all the methods for the type simplification of the trait. So exactly what we just talked about. Similarly, you could imagine that this pointy trait would be implemented for something like a U8 slice without the reference, where the metadata would be a U size that is the length of the thing.
[1:47:44] This is still very much like new and experimental. I do recommend you read through this RFC. It's really fascinating if you want to learn more about this. It has things like the trait alias thin, which is any type that implements pointy where the metadata is empty, which would be anything that doesn't have associated metadata in the pointer, so anything that is a thin pointer and not a fat pointer. And it has essentially methods for introspecting the metadata of a pointer, so that you can do things like actually look at the Vtable.
[1:48:16] There was some questions about this in chat earlier. This RFC would actually let you introspect that information and crucially construct Vtables on the fly. So you could have one that isn't known at compile time, but you build at runtime. And in fact, this already is something that exists one place in the standard library, as far as I know, which is for wakers in sort of the land of async. So the waker trait, we're not going to go too much into detail, but the waker trait, which I'll show you here.
[1:48:48] Um, the waker that's I'm lying. I mean the wake trade, uh, awake, not the wait, the raw wakers. Oh, there isn't a trade for it. That's why, um, let's go show you context actually. So context gives you a waker. Waker is a struct that has the methods wake, wake by ref, willWake, and fromRaw, and you can drop it and clone it.
[1:49:24] But in practice, waker is really generic. It's just that it isn't generic when you look at it. But inside of a waker is a raw waker. And a raw waker, if you look inside of it, is a data pointer and a vtable pointer. So it really is a data pointer. is dynamic dispatch but in sort of a hidden way and the vtable is a raw waker vtable and a raw waker vtable you construct by giving the function pointers for the clone method, for the wake method, for the wake by ref, and for drop.
[1:50:03] And so it's basically a manually constructed Vtable that gives you dynamic dispatch through a type rather than a trait. I'm not gonna go into too much detail of this, but I just wanted to show it as like an example of a manually constructed Vtable in the standard library. Is there anything more I wanted to talk about from here? I don't think so. All right, let's do questions because I've rented for a little while.
[1:50:38] I thought a reference to U8 had a start pointer and an end pointer, not a length. I think it has the length. It doesn't, the two are basically equivalent. You might be right, I forget. In fact, I wonder whether this reference says. Yes, you see, this RFC also deprecates the Trait object. stuff that exists in Nightly, because this is a replacement.
[1:51:11] Pointy trait, thin metadata, from raw parts. Where is the definition of... Oh, it doesn't actually give. Yeah, I was hoping it would say here what the actual associated metadata type is for slices, but I don't see it.
[1:51:42] I think it's just the length. Can we make our own types dynamically sized types? Sort of. So you can write this. foo here is now not sized. In fact, you can add more fields. You can't add a field after though. After this is not sized, right?
[1:52:14] So if I tried to do this, it'll tell me the size for values of u8 cannot be known at compile time. Only the last field of a struct may have a dynamically sized type. Change the fields type to have a statically known size. borrow types always have a statically known size. So what this is getting at is, if it's the last field, then think back to the argument I made very early on, right? If you have a non-size type in the middle here, and I asked you, like, if I want to look up like foo.x, and you only have a pointer to foo, how do you get a pointer to x when the type in the middle can have an arbitrary size?
[1:52:54] And the answer is you can't. You don't know how to get the address of x because t is arbitrarily sized. But if it's at the end, then it's fine. You can statically know the offset of f, the offset of x, and the offset of t. And the only information that's needed in order to make this sized would be the length of the last field. And so you are allowed to construct a type like this. This type is now not sized. But if you have an at foo, then that type will be sized by storing the pointer to the foo alongside with the length of t.
[1:53:34] So you can create your own dynamically sized types this way. Is box U8 the same thing as a vec U8? So this is if you have a box of a U8 slice, not behind a reference, is vec U8. They're not the same. So no. I guess let's do this.
[1:54:05] They're not the same. They feel the same, but they're not the same. Oops. Evacuate can grow. So evacuate, first of all, has, it's three words. It's the pointer to the vector on the heap. it's the length of the vector and it's the capacity of the vector. And this is so that if you try to push below the capacity, the length just gets incremented. If you try to push beyond the capacity, then the entire vector reallocates itself, copies over, and then changes.
[1:54:39] With a box U8, you can't do that. This will never grow or shrink. You can't push to it. It's just, think of it as a, it really is just a slice. You can turn a Vecuate into a Boxuate. And you can also go the other way around. But they're not the same, no. What's the difference between a dinfn and an fn?
[1:55:28] So basically, I can write a fnfoo that takes a dinfn. And I can write an fnbar that takes an fn. What's the difference between these? These are not the same. This has to be a function. It can't be a closure. And the reason for this is fn is really a function pointer.
[1:55:59] Like it's just a single pointer that has to be an address. This is a vtable. It's a trait object, which means that it both has a sort of the vtable you can think of here has a pointer to... calling the function, but it also has a data pointer, right? Because the the V, the structure of this is that it's a wide pointer, where one part is the V table, which has the pointer to call actually calling the function, but the other part is a data pointer. And crucially, the difference here is that if I have fn main, I can call foo with a closure.
[1:56:41] So I can do a function. This, but I can't do the same with bar. Why is it complaining? Oh. Right, so I can call foo with a closure because this captures x, right?
[1:57:16] So it's not just a function pointer, it's a function pointer and the data that the closure captures from its environment. That is, it needs to, when you call the closure, you also need to supply the address of x because it's needed by the body of the closure. and that's what's passed in the data part of the wide pointer. For bar, it requires an actual just function pointer, which means that you can't pass a closure because you wouldn't have anywhere to stick the data. When we use dinfn over implfn, yeah, so there's also bazf implfn.
[1:58:03] Um, and I can call Baz with a closure. What is it? What's it complaining about? I can call baz with a closure because remember, implfn is sort of sugar for a generic function over anything that is fn.
[1:58:34] So we actually get a concrete copy of baz for every type of closure that's passed in. And therefore, you can trivially pass in the data as well because it's monomorphized to each individual closure. The question then becomes, when do you use a dinfn, when do you use an implfn? The basic answer is... Implafen is more generally usable. Like you don't have to indirect behind a pointer, for example. But you end up generating a copy of Baz for each closure type you pass in, which might become quite a lot.
[1:59:12] And the other reason is because sometimes you want to take a trait object instead of making it generic because otherwise you have to propagate the generic type up. So imagine that I had a... struct wrapper, then internally I want it to contain a function pointer. If I have it hold, like I could write this, right? I could do this, but this means that anyone who wants to, any user of my library that wants to hold a wrapper would also themselves need to be generic over f or name the type of f.
[1:59:51] Whereas if this instead stored a box din fn, the now wrapper is no longer generic, so my callers don't have to think about and propagate that generic parameter. So sometimes it cleans up your interface and makes it just nicer to use. There's also the example of trait, making traits object safe. So if I have a trait x that has an fn foo, If I make this take an impl fn, then x is not object safe.
[2:00:28] I couldn't write a crocs. I guess let's have this take self. the trait x is not object safe because this is generic. implfn is equivalent to saying f is fn and this is f.
[2:01:01] And this cannot be made object safe like we talked about. But on the other hand, if I made this dinfn, It can be object safe because there is only one foo, right? So we don't have this problem of you need an infinite number of entries in the V table, there's only one foo and it itself takes a wide pointer, which then works for any type that can be a object safe. So there's not a clear cut answer here. Um, Nice.
[2:01:49] Okay, I think, I think that captures... everything I wanted to talk about. So the one thing that we didn't get around to talking about is coherence. I think coherence is different enough that we're not going to talk about it this stream and I might just do a separate stream on it, especially because we're on like the two hour mark. So I think this is a good time to stop.
[2:02:22] and then just do this separately. Are there any sort of questions towards the end about all the stuff we've talked about so far? Is the general difference between static dispatch and dynamic dispatch, the size trait, V tables, object safety, wide and fat pointers, does all of that roughly make sense now? Or is there anything more I can go through to sort of help crystallize it in your mind and make it clear why we have these, what they're for, what their limitations are? I'm happy to take some questions towards the end here.
[2:03:00] Could runtime trait detection be implemented in the future using a types of vtable? If I understand your question correctly, I don't think it can. So the idea is that can you take a trait object or can you take a wide pointer and figure out which traits it implements just by looking at its V table? I don't think you can. Part of the reason is because a different vtable gets generated for each trait object.
[2:03:37] So it's not like there's one vtable for str or for string, right? There are many vtables for string. There's one vtable for string for each din trait, right? Um, and so there's not just one, one V table that you could then look at to figure out what, what traits it implements. Um, like if you had like a find traits that took an S that was a din, like didn't trait, um, then the only things in the V table would be whatever methods are on the trait that you name here.
[2:04:24] You wouldn't get a V table of all possible methods on the provided type. So no, I don't think you can do dynamic detection of which traits something implements this way. Does calling a dinfn involve a double dereference, once for the Vtable pointer, once for the actual function pointer within, or does that get optimized away? So if I do call takes an F of Fn, and in here I do F.
[2:05:07] You know, that's a good question. I think it'll end up being a double D reference because you first have to go through... It's not quite a double D reference because this is a wide pointer, right? It's not, it's not a pointer to a tuple of a pointer and a V table, right? It it's really what gets passed in is a pointer to some T.
[2:05:39] You just don't know what the T is and a pointer to T's FN V table. That's really what's passed in here. And so this ends up calling like Vtable.call of t. And so there is a dereference here. Like, this is a pointer to the Vtable.
[2:06:12] So you do have to dereference the Vtable. I guess this is a better way to sort of type it out. So you do have to dereference the Vtable to get to the call. It's really, I guess, this, right? You have to dereference the V table to find the address of the call that you then call. So it does end up being two dereferences, but it's not quite pointer chasing either. It is true.
[2:06:58] Okay, so there is one thing that's a little bit funky, right? Which is if you have an X that takes an S of, let's say, din S ref str, then one thing you could do, and this was mentioned in chat, with the new pointer Vtable dynamic metadata RFC, you could imagine like, if s.Vtable is equal to string as din asrefster.Vtable, then like, s as reference f s dot data as reference to string dot i guess if this was a mute uh dot push right like maybe you could do some really weird ugly magic like this
[2:08:02] I would recommend just don't do it. But yeah, you could imagine you could compare V tables this way. I don't know if this is even a guarantee that the compiler will uphold that a type will always have only exactly one V table. And yeah, the compiler does do a decent amount of optimization here too. Like if you do a box din FN, I think it like might not do a heap allocation always if you like, if just like escape analysis and stuff. But in general, if you use generics, like if you use an actual generic type parameter or an impl block, sorry, an impl trait, In those cases, you will get better optimization just because the compiler gets full insight at compile time into what all the relevant types are and can co-optimize based on the actual concrete implementations.
[2:08:52] Whereas once you have indirection through dynamic dispatch, the compiler loses some of the information it would otherwise have and be able to optimize based on. Can you do a quick example of the sliceVec of DINs? Oh, yeah. Say hi's. So if you actually wanted to do like, I guess we had DIN hi, but let's make it DIN asref stir. Then you wanted like for H and S.
[2:09:27] Let's make it V. For S and V, S.asref. Um, so to actually get this to work, uh, what you end up with is you have to do this, um, to make the sized, right. Um, so that all of the elements of the array are the same size because the raise required that so that you can find the given index. Right. Um, and once you do that, um, the salt just works.
[2:09:59] And you could put a box or arc or whatever for the inner type too. Different compilation units can lead to different V tables. That sounds about right. So this is a little bit anecdotal, but when you compile Rust code, Rust might compile one crate using multiple independent threads to compile different subsets of the crate to sort of speed up compilation. But because you want those separate units to work in like entirely concurrently without too much synchronization, they might both encounter, let's say, a...
[2:10:37] string being used as a din-asref, they might both generate their own vtables because they don't want to coordinate about generating the vtables and therefore you have multiple vtables even for the same type for the same trait. So that's one example why that invariant might not hold. That's a good point. And yeah, there is also any, which I haven't talked about. I'm not going to actually demo it, but so there's the any trait. And any is super magical.
[2:11:09] It's not actually like any is just a trait that has a function that returns an identifier for a type. that is unique, guaranteed by the compiler. And so if you have something that's a trait object over any, you can use type ID on it because it gets added to the V table to get a unique... type identifier for that value and then you can use that to downcast from a din any to the concrete type because we know what the type identifier is i'm not going to go into any too much but but any uses a lot of the stuff that we've talked about so far to actually be able to go from a din a dim trait as long as that trait includes any into a reference to the actual underlying type.
[2:12:02] It's really cool and actually surprisingly simple now that you know what you know. So I recommend you give a read to the standard AnyModule documentation. It talks about why this is safe. Alright, I think we're going to end it there. 2 hours and 15, I'm pretty happy with that. We covered a lot. I hope that was useful. I hope you feel like you learned something and some of this might actually stick. I have made a little bit of progress on my coding live stream that I really want to happen.
[2:12:36] I'm hoping it'll happen sooner rather than later, but it has not escaped me. I'm still on the case. Thanks all for coming out and I will see you next time. So long farewell!
在 Vidleaf 工作台中打开
搜索转录文本、选择行、复制带时间戳的引文、翻译。
署名
《Crust of Rust:分发与胖指针》,作者 Jon Gjengset(https://www.youtube.com/@jonhoo),依据 CC BY 4.0 许可(https://creativecommons.org/licenses/by/4.0/)。源视频:https://www.youtube.com/watch?v=xcygqF5LVmM。本页为该视频的文本转录,添加了段落分隔和时间戳;创作者与 Vidleaf 无关联,也不为其背书。Vidleaf 添加了 AI 标点和 AI 生成的摘要;原始措辞仍可在本页查看。
您是创作者或权利持有人吗?请求更正或移除:copyright@vidleaf.app(参见关于这些页面)。
最后更新于