07-1 Option枚举方法

07-1 Option枚举方法

------正文内容展示,开始汲取新知识啦------

impl<T> Option<T>

pub const fn is_some(&self) -> bool

#![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

#![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

#![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>

#![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:?}");
}
温馨提示:本文最后更新于2024-05-04 11:00:22,某些文章具有时效性,若有错误或已失效,请在下方留言或QQ联系站长
------正文内容展示,开始汲取新知识啦------

感谢您的访问,Ctrl+D收藏本站吧。

© 版权声明
THE END
喜欢就支持一下吧
点赞6赞赏 分享
评论 共1条

请登录后发表评论