thiserror

toml

thiserror = "2.0"

rs

use std::io::Read;
use std::{fs,io};
use thiserror::Error;

#[derive(Debug,Error)]
enum MyError{
    #[error("")]
    IoError(#[from] io::Error),
    #[error("xxxxx in {0}")]
    EmptyUserName(String),
}
//没有文件会报ioerror 文件为空会报emptyusername得错
fn read_username(path: &str) -> Result<String, MyError> {
    let mut username = String::with_capacity(100);
    fs::File::open(path)?.read_to_string(&mut username)?;
    if username.is_empty() {
        return Err(MyError::EmptyUserName(String::from(path)));
    }
    Ok(username)
}

fn main(){
  match read_username("count.dat") {
      Ok(user) => println!("xxx, {user}"),
      Err(e) => println!("{e:?}")
  }
}
posted @   朝阳1  阅读(4)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示