垠的备忘录

Rust 的反向类型推导

Yin Wang's avatar
Yin Wang
Dec 08, 2023
∙ Paid

继续看 Rust 文档,发现一个例子,说 Rust 的类型推导是有“反向推导”的。的确如此,这个例子里的数组没有标注成员的类型,然后根据后面的语句 push 进去的一个元素,反向“推导”出了整个数组就是 [u8] (8 位无符号整数)的类型。

下面的文字说,不用写类型,编译器和程序员都高兴。No type annotation of variables was needed, the compiler is happy and so is the programmer!

真的如此吗?其实这里不写数组的类型,阅读的时候你就得每次都去想这个数组里是什么类型。要等到你看到下面那个 push,还得再跳回去看一下 elem 是什么类型,才能知道数组里面都是 u8 类型。这就是在做“人脑类型推导”。而且你不止要做一次…

User's avatar

Continue reading this post for free, courtesy of Yin Wang.

Or purchase a paid subscription.
© 2026 Yin Wang · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture