知识卡片
as转换不保证信息保留
as可在语言支持的类型对之间转换,也可能截断或改变数值信息。u32转u16即使某次值9能放下,也不说明任意输入安全。通常优先From/Into或TryFrom/TryInto;确需底层转换语义时再使用as,并写清范围与目的。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Casts · 查看原书依据
lossy conversions:14 let x: u32 = 9; let y = x as u16; which would be rejected by the from/into versions: error[E0277]: the trait bound `u16: From<u32>` is not satisfied --> src/main.rs:136:20 | 136 | let y: u16 = x.into(); | ^^^^ the trait `From<u32>` is not implemented for `u16` | = help: the following other types implement trait `From<T>`: <u16 as From<No
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Casts》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u033-ch01-042)。
- 结论依据:原文在“lossy conversions”附近的定义、例子或代码支撑本卡核心说明:as可在语言支持的类型对之间转换,也可能截断或改变数值信息。边界按已读前提解释;示例未执行。
- 原始内容:lossy conversions:14 let x: u32 = 9; let y = x as u16; which would be rejected by the from/into versions: error[E0277]: the trait bound `u16: From<u32>` is not satisfied --> src/main.rs:136:20 | 136 | let y: u16 = x.into(); | ^^^^ the trait `From<u32>` is not implemented for `u16` | = help: the following other types implement trait `From<T>`: <u16 as From<No