由于 Rust 没有 None
/null
/nil
值,我如何表示数组中缺失或无效的值?
最佳答案
这就是全部discussed in The Rust Programming Language 。请确保您通读该书;我们花了很多时间来解决新来者的许多问题和担忧。
Since Rust does not have
None
我不知道你为什么这么说,考虑到 Option
(以及扩展名 Option::None
)是 Rust 的一个关键部分。其实太重要了,导入in the prelude .
如果您想要一个包含一个“缺失”值的数组:
let color = [Some(255), None, Some(255)];
在许多具有 nil/null 概念的语言中,每个值都可以是您期望的类型或特殊类型 nil/null。这在 Rust 中并非如此——a Foo
和一个Option<Foo>
是不同的类型,您不能“忘记”处理缺失的值:
let sum = color[0] + color[1];
error[E0369]: binary operation `+` cannot be applied to type `std::option::Option<{integer}>`
--> src/main.rs:4:15
|
4 | let sum = color[0] + color[1];
| ^^^^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Add` might be missing for `std::option::Option<{integer}>`
您必须在 Option
上使用模式匹配或辅助方法(在内部进行模式匹配)来“解压”值并明确处理 Some
和None
案例。
另请参阅:
关于types - 如何表示缺失或无效的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47097990/