知识卡片
缺失进入类型系统
接口可能无值时,Option 用 Some(T) 和 None 表示在场与缺失。i8 与 Option 的类型不同,后者不能直接参加普通整数加法,调用者必须给缺失分支确定行为。若上下文没有给出 T,单写 None 也不足以让编译器推断其类型。
相关卡片 [[枚举统一互斥变体]]、[[匹配必须覆盖全域]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 枚举与模式匹配 The Option Enum and Its Advantages Over Null Values · 查看原书依据
In short, because Option<T> and T (where T can be any type) are different types, the compiler won’t let us use an Option<T> value as if it were definitely a valid value. For example, this code won’t compile, because it’s trying to add an i8 to an Option<i8>:
参考来源
- 位置:《The Rust Programming Language(第2版)》第06章 枚举与模式匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c06.xhtml`,块 0061)
- 结论依据:编译失败示例明确区分普通值和可能缺失的值,说明处理缺失的义务来自类型。
- 原始内容:In short, because Option<T> and T (where T can be any type) are different types, the compiler won’t let us use an Option<T> value as if it were definitely a valid value. For example, this code won’t compile, because it’s trying to add an i8 to an Option<i8>: