zoukankan      html  css  js  c++  java
  • 【Rust】标准库问号

    环境

    • Rust 1.56.1
    • VSCode 1.61.2

    概念

    参考:https://doc.rust-lang.org/stable/rust-by-example/std/result/question_mark.html

    示例

    main.rs

    mod checked {
        #[derive(Debug)]
        enum MathError {
            DivisionByZero,
            NonPositiveLogarithm,
            NegativeSquareRoot,
        }
    
        type MathResult = Result<f64, MathError>;
    
        fn div(x: f64, y: f64) -> MathResult {
            if y == 0.0 {
                Err(MathError::DivisionByZero)
            } else {
                Ok(x / y)
            }
        }
    
        fn sqrt(x: f64) -> MathResult {
            if x < 0.0 {
                Err(MathError::NegativeSquareRoot)
            } else {
                Ok(x.sqrt())
            }
        }
    
        fn ln(x: f64) -> MathResult {
            if x <= 0.0 {
                Err(MathError::NonPositiveLogarithm)
            } else {
                Ok(x.ln())
            }
        }
    
        fn op_(x: f64, y: f64) -> MathResult {
            let ratio = div(x, y)?;
            let ln = ln(ratio)?;
            sqrt(ln)
        }
    
        pub fn op(x: f64, y: f64) {
            match op_(x, y) {
                Err(why) => panic!(
                    "{}",
                    match why {
                        MathError::NonPositiveLogarithm => "logarithm of non-positive number",
                        MathError::DivisionByZero => "division by zero",
                        MathError::NegativeSquareRoot => "square root of negative number",
                    }
                ),
                Ok(value) => println!("{}", value),
            }
        }
    }
    
    fn main() {
        checked::op(1.0, 10.0);
    }
    

    总结

    了解了 Rust 中问号的使用方式,可以解开 Result。

    附录

  • 相关阅读:
    POJ2960 S-Nim
    HDU1850 Being a Good Boy in Spring Festival
    描述性统计-1
    基础-1
    .Net程序调试
    家装设计
    ACDSee技巧
    Timeline Maker 用法小结
    Windows 7 操作系统核心文件
    艺术字的操作
  • 原文地址:https://www.cnblogs.com/jiangbo44/p/15743975.html
Copyright © 2011-2022 走看看