Rust 标准库 API Result

Rust About 769 words

自定义 Reuslt

type Result<T> = std::result::Result<T, Box<dyn error::Error>>;

? 运算符

这里返回的Result是使用了type自定义的类型。

fn test() -> Result<i32> {
    let result: result::Result<i32, _> = "123".parse::<i32>();
    let result: result::Result<i32, ParseIntError> = "123".parse::<i32>();
    let result1 = "123".parse::<i32>()?;
    Ok(1)
}

fn test2() -> Result<usize>{
    let mut s = String::new();
    let i: usize = File::open("Cargo.toml")?.read_to_string(&mut s)?;
    println!("{}", s);
    Ok(1)
}

match 匹配

fn main() {
    let i = test().unwrap();

    match test2() {
        Ok(n) => {
            println!("{}", n)
        }
        Err(e) => {
            println!("{:?}", e);
        }
    }
}
Views: 1,036 · Posted: 2023-04-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh