如果函数返回一个可选值,我不想采取任何行动;如何仅测试None
情况? 这段代码可以运行,但看起来很糟糕。
let v = ffunc();
match v {
None => { callproc() },
Some(x) => { }
}
在 C 语言中,我可以这样写:
int x = ffunc();
if ( !x ) { callproc() }
如果函数返回一个可选值,我不想采取任何行动;如何仅测试None
情况? 这段代码可以运行,但看起来很糟糕。
let v = ffunc();
match v {
None => { callproc() },
Some(x) => { }
}
在 C 语言中,我可以这样写:
int x = ffunc();
if ( !x ) { callproc() }
要检查一个Option
是否为None
,可以使用Option::is_none
或使用if let
语法。
例如:
let x = ffunc();
if let None = x {
println!("x is None")
}
或者使用 Option::is_none
函数:
let x = ffunc();
if x.is_none() {
println!("x is None")
}
if x == None
。 - ShepmasterOption<T>
中的 T
实现了 PartialEq
时才成立。 - hellowSome(x)
,请执行以下操作:let v = ffunc()
if let Some(x) = v {
func_to_use_x(x);
} else {
callproc();
}
如果您不在意选项中的值,那么:if v.is_none() {...}
或者if v.is_some() {...}
如果您想在 Option
的值为 None
时插入一个值,并在否则情况下获取该值,您可以使用 get_or_insert
let mut x = None;
let y = x.get_or_insert(5);
assert_eq!(y, &5);
assert_eq!(x, Some(5));
或者使用 get_or_insert_with
进行延迟评估:
let mut x = None;
let y = x.get_or_insert_with(|| 5);
assert_eq!(y, &5);
assert_eq!(x, Some(5));
您也可以使用or
和or_else
返回一个新的Option
,而不是改变原始值:
let x = None;
assert_eq!(x.or(Some(100)), Some(100));
let x = None;
assert_eq!(x.or_else(|| Some(100)), Some(100));