该Option类型定义为:
enum Option<T> {
None,
Some(T),
}
Run Code Online (Sandbox Code Playgroud)
这意味着该Option类型可以有一个None或一个Some值。
也可以看看:
小智 5
不,它们不相同,并且将它们视为相同的文档要么是错误的,要么是您的误解。Option是一种类型(更准确地说,是泛型类型构造函数;Option<i32>是一种类型,因此也是Option<String>)。Some是一个构造函数。除了充当函数之外fn Some<T>(T x) -> Option<T>,它还用于模式匹配:
let mut opt: Option<i32>; // type
opt = Some(1); // constructor
opt = None; // other constructor
match opt {
Some(x) => {
// pattern
println!("Got {}", x);
}
None => {
// other pattern
println!("Got nothing");
}
}
Run Code Online (Sandbox Code Playgroud)