Rust 标准库 API Option

Rust About 1,169 words

源码

Option是一个范型枚举,有NoneSome两个字段。

pub enum Option<T> {

    None,

    Some(T),
}

is_some 判断是否是 Some

let option: Option<i32> = Some(123);
let is_some: bool = option.is_some();

is_none 判断是否是 None

let option: Option<i32> = Some(123);
let is_none: bool = option.is_none();

match 匹配

match Some(100) {
    Some(50) => println!("50"),
    Some(x) => println!("{}", x),
    None => println!("none"),
}

if let 匹配

let option: Option<i32> = Some(123);

if let Some(50) = option {
    println!("found some=50");
} else if let Some(x) = option {
    println!("found some={}", x);
} else {
    println!("found none");
}

expect

let i: i32 = Some(123).expect("must be i32");

unwarp

let i1: i32 = Some(123).unwrap();
let i2: i32 = Some::<u16>(123).unwrap_or(0);
let i3: i32 = None::<i32>.unwrap_or_default();
let i4: i32 = Some(123).unwrap_or_else(|| 666);

take

Option中取出值,将原来的Option变为None

// Takes the value out of the option, leaving a None in its place.
let mut option = Some(123);
// let mut option = None;
let take_option: Option<i32> = option.take();

println!("{:?}", option);
println!("{:?}", take_option);

输出

None
Some(123)
Views: 942 · Posted: 2023-04-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh