【Rust Course】读书笔记-可恢复的错误 Result

39 阅读1分钟

提问

如何处理错误错误返回

回答

使用Rustlt<T,E> 用match分别处理Ok 和Err

use std::fs::File;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(error) => {
            panic!("Problem opening the file: {:?}", error)
        },
    };
}
  • 失败就崩溃
    • unwrap
    • expect 可以附加自定义信息
use std::fs::File;

fn main() {
    let f = File::open("hello.txt").unwrap();
    let f = File::open("hello.txt").expect("Failed to open hello.txt");
}
  • 错误传播 ? 使用统一的错误返回 io::Error是错误的基类 使用?将其他错误转换为io::Erro
use std::fs::File;
use std::io;
use std::io::Read;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();

    File::open("hello.txt")?.read_to_string(&mut s)?;

    Ok(s)
}