什么是有和无? [英] What are Some and None?
问题描述
我在使用 Vec::get
时遇到了一些我不理解的输出.代码如下:
I came across some output I don't understand using Vec::get
. Here's the code:
fn main() {
let command = [('G', 'H'), ('H', '5')];
for i in 0..3 {
print!(" {} ", i);
println!("{:?}", command.get(i));
}
}
输出是
0 Some(('G', 'H'))
1 Some(('H', '5'))
2 None
我之前接触过 Haskell,我的意思是在一个教程网站上看了 10 分钟,然后又跑回 C++,但我记得我读过一些关于 Some
和 None
用于 Haskell.我很惊讶在 Rust 中看到这个.有人能解释一下为什么 .get()
返回 Some
或 None
吗?
I've dabbled in Haskell before, and by that I mean looked at a tutorial site for 10 minutes and ran back to C++, but I remember reading something about Some
and None
for Haskell. I was surprised to see this here in Rust. Could someone explain why .get()
returns Some
or None
?
推荐答案
get
的签名(对于 slice,not Vec
,因为您正在使用数组/切片)是
The signature of get
(for slices, not Vec
, since you're using an array/slice) is
fn get(&self, index: usize) -> Option<&T>
也就是说,它返回一个 Option
,这是一个像
That is, it returns an Option
, which is an enum defined like
pub enum Option<T> {
None,
Some(T),
}
None
和 Some
是枚举的变体,即Option
类型的值code> 可以是 None
,也可以是包含 T
类型值的 Some
.您也可以使用变体创建 Option
枚举:
None
and Some
are the variants of the enum, that is, a value with type Option<T>
can either be a None
, or it can be a Some
containing a value of type T
. You can create the Option
enum using the variants as well:
let foo = Some(42);
let bar = None;
这个和核心一样data 也许a = Nothing |只是一个
Haskell 类型;两者都代表一个可选值,要么存在 (Some
/Just
),要么不存在 (None
/Nothing
).
This is the same as the core data Maybe a = Nothing | Just a
type in Haskell; both represent an optional value, it's either there (Some
/Just
), or it's not (None
/Nothing
).
这些类型通常用于表示失败的原因只有一种可能性,例如,.get
使用 Option
来提供类型安全的边界检查数组访问:当索引越界时返回None
(即无数据),否则返回包含请求指针的Some
.
These types are often used to represent failure when there's only one possibility for why something failed, for example, .get
uses Option
to give type-safe bounds-checked array access: it returns None
(i.e. no data) when the index is out of bounds, otherwise it returns a Some
containing the requested pointer.
另见:
这篇关于什么是有和无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!