《Rust权威指南》第9章_错误处理_草稿

本文介绍了Rust编程中如何处理不可恢复的错误(使用panic!宏)和可恢复错误(使用Result枚举)。通过示例展示了如何匹配错误、使用unwrap或expect方法以及如何优雅地传播错误。还讨论了何时应该使用panic!,并提供了错误处理的指导原则,包括自定义错误类型的创建。
摘要由CSDN通过智能技术生成
  • 不可恢复错误与panic!
    • 使用panic!产生的回溯信息
  • 可恢复错误与Result
    • 匹配不同的错误
    • 失败时触发panic的快捷方式:unwarp和expect
    • 传播错误
      • 传播错误的快捷方式:?运算符
      • ?运算符只能被用于返回Result的函数
  • 要不要使用panic!
    • 示例、原型和测试
    • 当你比编译器拥有更多信息
    • 错误处理的指导原则
    • 创建自定义类型来进行有效性验证
//Powershell输入
// $env:RUST_TRACE=1;cargo run
//来显示回溯信息

use std::fs::File;
use std::io::ErrorKind;
use std::io;
use std::io::Read;
use std::fs;
use std::error::Error;

pub struct Guess {
    value:i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 || value > 100 {
            panic!("Guess value must be between 1 and 100, got {}.", value);
        }
        Guess {
            value
        }
    }
     pub fn value(&self) -> i32 {
         self.value
     }
}

fn read_username_from_file_1() -> Result<String, io::Error> {
    let f = File::open("hello.txt");
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut s =String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

fn read_username_from_file_2() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s);
}

fn read_username_from_file_3() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}

fn read_username_from_file_4() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt");
}

fn read_username_from_file_5() -> Result<(), Box<dyn Error>> {
    let f = File::open("hello.txt");
    Ok(())
}

fn main() {
    //直接调用panic!宏
    //panic!("crash and burn");

    //let v = vec![1, 2, 3];
    // v[99];

    //let f: u32 = File::open("hello.txt");

    let f = File::open("hello.txt");
    let f = match f {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create(("hello.txt")) {
                Ok(fc) => fc,
                Err(e) => panic!("Tried to create file but there was a problem: {:?}", e),
            },
            other_error => panic!("There was a problem opening the file: {:?}", other_error),
        },
    };

    let f = File::open("hello.txt").map_err(|error| {
        if error.kind() == ErrorKind::NotFound {
            File::create("hello.txt").unwrap_or_else(|error| {
                panic!("Tried to create file but there was a problem: {:?}", error);
            })
        } else {
            panic!("There was a problem opening the file: {:?}", error);
        }
    });

    let f = File::open("hello.txt").unwrap();

    let f = File::open("hello.txt").expect("Failed to open hello.txt");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值