ICode9

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

【Rust】结果枚举(二)

2022-05-28 14:01:03  阅读:26  来源: 互联网

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


环境

  • Time 2022-03-25
  • Rust 1.59.0

示例

as_deref

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

iter

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

expect

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

unwrap

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

unwrap_or_default

fn main() {
    let result: Result<&str, u32> = Err(44);
    println!("{:?}", result.unwrap_or_default());
}

expect_err

fn main() {
    let result: Result<&str, u32> = Err(44);
    println!("{:?}", result.expect_err("OK"));
}

unwrap_err

fn main() {
    let result: Result<&str, u32> = Err(44);
    println!("{:?}", result.unwrap_err());
}

and

fn main() {
    let result: Result<u32, u32> = Ok(44);
    println!("{:?}", result.and(Ok(4)));
}

and_then

fn main() {
    let result: Result<u32, u32> = Ok(44);
    let result: Result<u32, u32> = result.and_then(|e| Err(e * 2));
    println!("{:?}", result);
}

总结

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

附录

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

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

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

ICode9版权所有