impl<T> Option<T>
pub const fn is_some(&self) -> bool
判断option类型是否是Some变体,返回布尔类型
#![allow(unused)]
fn main() {
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);
let x: Option<u32> = None;
assert_eq!(x.is_some(), false);
}
pub fn is_some_and(&self, f: impl FnOnce(&T) -> bool) -> bool
判断option类型是否是Some变体,并且其包含的值是否符合断言条件,返回布尔类型
#![allow(unused)]
#![feature(is_some_with)]
fn main() {
let x: Option<u32> = Some(2);
assert_eq!(x.is_some_and(|&x| x > 1), true);
let x: Option<u32> = Some(0);
assert_eq!(x.is_some_and(|&x| x > 1), false);
let x: Option<u32> = None;
assert_eq!(x.is_some_and(|&x| x > 1), false);
}
注:pub fn is_some_with(&self, f: impl FnOnce(&T) -> bool) -> bool
与上方api功能一致,但仅限于在nightly
版本中使用
pub const fn is_none(&self) -> bool
判断option类型是否是None变体,返回布尔类型
#![allow(unused)]
fn main() {
let x: Option<u32> = Some(2);
assert_eq!(x.is_none(), false);
let x: Option<u32> = None;
assert_eq!(x.is_none(), true);
}
pub const fn as_ref(&self) -> Option<&T>
将 &Option<T> 转换成 Option<&T>
#![allow(unused)]
fn main() {
let text: Option<String> = Some("Hello, world!".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Option<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");
}
感谢您的访问,Ctrl+D收藏本站吧。
© 版权声明
THE END
暂无评论内容