zoukankan      html  css  js  c++  java
  • 【Rust】包装错误

    环境

    • Rust 1.56.1
    • VSCode 1.61.2

    概念

    参考:https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html

    示例

    main.rs

    use std::error;
    use std::error::Error as _;
    use std::fmt;
    use std::num::ParseIntError;
    
    type Result<T> = std::result::Result<T, DoubleError>;
    
    #[derive(Debug)]
    enum DoubleError {
        EmptyVec,
        // 包装额外的错误
        Parse(ParseIntError),
    }
    
    impl fmt::Display for DoubleError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match *self {
                DoubleError::EmptyVec => write!(f, "please use a vector with at least one element"),
                DoubleError::Parse(..) => write!(f, "the provided string could not be parsed as int"),
            }
        }
    }
    
    impl error::Error for DoubleError {
        fn source(&self) -> Option<&(dyn error::Error + 'static)> {
            match *self {
                DoubleError::EmptyVec => None,
                DoubleError::Parse(ref e) => Some(e),
            }
        }
    }
    
    impl From<ParseIntError> for DoubleError {
        fn from(err: ParseIntError) -> DoubleError {
            DoubleError::Parse(err)
        }
    }
    
    fn double_first(vec: Vec<&str>) -> Result<i32> {
        let first = vec.first().ok_or(DoubleError::EmptyVec)?;
        let parsed = first.parse::<i32>()?;
    
        Ok(2 * parsed)
    }
    
    fn print(result: Result<i32>) {
        match result {
            Ok(n) => println!("The first doubled is {}", n),
            Err(e) => {
                println!("Error: {}", e);
                if let Some(source) = e.source() {
                    println!("  Caused by: {}", source);
                }
            }
        }
    }
    
    fn main() {
        let numbers = vec!["42", "93", "18"];
        let empty = vec![];
        let strings = vec!["tofu", "93", "18"];
    
        print(double_first(numbers));
        print(double_first(empty));
        print(double_first(strings));
    }
    

    总结

    了解了 Rust 中,可以定义错误的枚举,然后返回其中的一个错误。

    附录

  • 相关阅读:
    网络流 KM dinic
    网络流 增广路 回退
    树链剖分
    线段树区间更新 lazy
    全排列
    各种蕴含算法思想的DP
    各种蕴含算法思想的DP
    Strassen矩阵乘法之思考
    [0,x)的随机数
    hdu1331 按着题目的公式直接写
  • 原文地址:https://www.cnblogs.com/jiangbo44/p/15727724.html
Copyright © 2011-2022 走看看