为什么 Option<NonZeroU32> 不需要使用明确的 Some?
Why does Option<NonZeroU32> not require using explicit Some?
我无意中注意到以下代码可以编译并运行,但我很好奇为什么?
我明白为什么 u32 的 Option 需要一个显式的 Some,但我不明白为什么 NonZeroU32 是特殊的并且实际上禁止显式使用 Some。
use std::num::NonZeroU32;
fn main() {
let x : Option<u32> = Some(1);
//let y : Option<NonZeroU32> = Some(NonZeroU32::new(2)); //doesn't compile
let y : Option<NonZeroU32> = NonZeroU32::new(2);
println!("{} {}", x.unwrap(), y.unwrap());
}
我试着在 https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html 中查找
和 https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#25-155
我注意到有
#[rustc_nonnull_optimization_guaranteed]
我认为这就是为什么不需要显式 Some 的原因,但我缺乏经验来证实我的理论。
不,这是因为 NonZeroU32::new()
已经 returns Option<NonZeroU32>
(它 returns None
如果给定零)。
NonZeroU32::new()
return None
如果参数 n
为零。 Option
是函数的失败指示符。这是 Rust 中非常常见的模式,与 rustc_nonnull_optimization_guaranteed
无关
我无意中注意到以下代码可以编译并运行,但我很好奇为什么? 我明白为什么 u32 的 Option 需要一个显式的 Some,但我不明白为什么 NonZeroU32 是特殊的并且实际上禁止显式使用 Some。
use std::num::NonZeroU32;
fn main() {
let x : Option<u32> = Some(1);
//let y : Option<NonZeroU32> = Some(NonZeroU32::new(2)); //doesn't compile
let y : Option<NonZeroU32> = NonZeroU32::new(2);
println!("{} {}", x.unwrap(), y.unwrap());
}
我试着在 https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html 中查找 和 https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#25-155
我注意到有
#[rustc_nonnull_optimization_guaranteed]
我认为这就是为什么不需要显式 Some 的原因,但我缺乏经验来证实我的理论。
不,这是因为 NonZeroU32::new()
已经 returns Option<NonZeroU32>
(它 returns None
如果给定零)。
NonZeroU32::new()
return None
如果参数 n
为零。 Option
是函数的失败指示符。这是 Rust 中非常常见的模式,与 rustc_nonnull_optimization_guaranteed