【Rust】结果枚举(一)

环境

  • Time 2022-03-24
  • Rust 1.59.0

示例

is_ok

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.is_ok());
}

is_err

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.is_err());
}

ok

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.ok());
}

err

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.err());
}

as_ref

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.as_ref());
}

map

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.map(|e| e / 4));
}

map_or

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.map_or(22, |e| e / 4));
}

map_or_else

fn main() {
    let result: Result<i32, &str> = Ok(44);
    println!("{:?}", result.map_or_else(|_| 2, |e| e / 4));
}

map_err

fn main() {
    let result: Result<i32, &str> = Err("error");
    println!("{:?}", result.map_err(|e| format!("[{}]", e)));
}

总结

了解了结果枚举中相关的一些方法。

附录

posted @ 2022-05-28 13:42  jiangbo4444  阅读(47)  评论(0编辑  收藏  举报