知识卡片
类型推断由用法约束
函数签名和表达式的用途能约束局部变量的类型。例如 grade_cutoffs 返回 Vec<u32>,于是其中存入的值必须为 u32。再结合 tier_size: u32,编译器就能确定乘减运算及循环范围中的整数类型。手写这些局部标注与交给编译器推断生成相同的机器代码。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Fundamental Types 从源码的类型约束读到机器表示 · 查看原书依据
These two definitions are exactly equivalent, and Rust will generate the same machine code either way.
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第02章《Fundamental Types》|从源码的类型约束读到机器表示,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch02.xhtml#fundamental-types`
- 结论依据:原文给出同一个函数的全显式和局部推断写法,说明二者等价,类型错误仍在编译期检查。
- 原始内容:These two definitions are exactly equivalent, and Rust will generate the same machine code either way.