知识卡片
可失败转换使用Try系列
From与Into表达应当成功的值转换,TryFrom与TryInto则返回Result并指定失败类型。缩窄整数范围可能失败,应让调用者处理该结果,而不是在转换内部偷偷unwrap。若转换本来总能成功,标准库可用Infallible表达其Try转换没有错误值。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types User-Defined Type Conversions · 查看原书依据
TryFrom<T> Items of this type can be built from items of type T, but the conversion might not succeed. Into<T> Items of this type can be converted into items of type T, and the conversion always succeeds. TryInto<T> Items of this type can be converted into items of type T, but the conversion might not succeed. Given the discussion in Item 1 about expressing
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《User-Defined Type Conversions》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u032-ch01-039)。
- 结论依据:原文在“TryFrom<T>”附近的定义、例子或代码支撑本卡核心说明:From与Into表达应当成功的值转换,TryFrom与TryInto则返回Result并指定失败类型。边界按已读前提解释;示例未执行。
- 原始内容:TryFrom<T> Items of this type can be built from items of type T, but the conversion might not succeed. Into<T> Items of this type can be converted into items of type T, and the conversion always succeeds. TryInto<T> Items of this type can be converted into items of type T, but the conversion might not succeed. Given the discussion in Item 1 about expressing