检查 Option 是否包含特定 Some 值的最佳方法?
Best way to check if Option contains a specific Some value?
你不能做这样的事情:
if option.is_some() && option == 1 {
// ...
}
因为如果 option.is_some() == false
第二次比较会出错。
做这样的事情最好的方法是什么?
我现在在做什么:
if option.is_some() {
if option == 1 {
// ...
}
}
模式匹配是一个强大的工具,使用它!使用 if let
:
而不是常规 if
if let Some(1) = option {
// --snip--
}
关于模式匹配的更多信息,请参考The Rust Reference。
模式匹配是正确的解决方案,但如果你想要bool
,你可以使用相等运算符:
fn main() {
let maybe_int = Some(123);
let contains_123: bool = maybe_int == Some(123);
assert!(contains_123);
}
你不能做这样的事情:
if option.is_some() && option == 1 {
// ...
}
因为如果 option.is_some() == false
第二次比较会出错。
做这样的事情最好的方法是什么?
我现在在做什么:
if option.is_some() {
if option == 1 {
// ...
}
}
模式匹配是一个强大的工具,使用它!使用 if let
:
if
if let Some(1) = option {
// --snip--
}
关于模式匹配的更多信息,请参考The Rust Reference。
模式匹配是正确的解决方案,但如果你想要bool
,你可以使用相等运算符:
fn main() {
let maybe_int = Some(123);
let contains_123: bool = maybe_int == Some(123);
assert!(contains_123);
}