ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【Rust】结果枚举(一)

2022-05-28 14:02:26  阅读:31  来源: 互联网

标签:结果 println 枚举 let result fn main Rust Result


环境

  • 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)));
}

总结

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

附录

标签:结果,println,枚举,let,result,fn,main,Rust,Result
来源: https://www.cnblogs.com/jiangbo4444/p/16320522.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有