知识卡片
整数转换需要明确意图
Rust区分整数符号和位宽,并要求不同整数类型之间明确转换。i32的42即使能装进i16,也不能直接赋值;扩大为i64也需选择转换方式。可失败缩窄应处理结果,不能因编译器建议unwrap就默认panic是合适的失败策略。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Fundamental Types · 查看原书依据
Rust also doesn’t allow some things that might appear “safe,” such as putting a value from a smaller integer type into a larger integer type: let x = 42i32; // Integer literal with type suffix let y: i64 = x; error[E0308]: mismatched types --> src/main.rs:36:18 | 36 | let y: i64 = x; | --- ^ expected `i64`, found `i32` | | | expected due to this | help: you
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Fundamental Types》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u008-ch01-001)。
- 结论依据:原文在“Rust also doesn’t allow”附近的定义、例子或代码支撑本卡核心说明:Rust区分整数符号和位宽,并要求不同整数类型之间明确转换。边界按已读前提解释;示例未执行。
- 原始内容:Rust also doesn’t allow some things that might appear “safe,” such as putting a value from a smaller integer type into a larger integer type: let x = 42i32; // Integer literal with type suffix let y: i64 = x; error[E0308]: mismatched types --> src/main.rs:36:18 | 36 | let y: i64 = x; | --- ^ expected `i64`, found `i32` | | | expected due to this | help: you