• 【Rust】可选和错误


    环境

    • Rust 1.56.1
    • VSCode 1.61.2

    概念

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

    示例

    返回 Option

    use std::num::ParseIntError;
    
    fn double_first(vec: Vec<&str>) -> Option<Result<i32, ParseIntError>> {
        vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n))
    }
    
    fn main() {
        let numbers = vec!["42", "93", "18"];
        let empty = vec![];
        let strings = vec!["tofu", "93", "18"];
    
        println!("The first doubled is {:?}", double_first(numbers));
        println!("The first doubled is {:?}", double_first(empty));
        println!("The first doubled is {:?}", double_first(strings));
    }
    

    返回 Result

    use std::num::ParseIntError;
    
    fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
        let opt = vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n));
        opt.map_or(Ok(None), |r| r.map(Some))
    }
    
    fn main() {
        let numbers = vec!["42", "93", "18"];
        let empty = vec![];
        let strings = vec!["tofu", "93", "18"];
        println!("The first doubled is {:?}", double_first(numbers));
        println!("The first doubled is {:?}", double_first(empty));
        println!("The first doubled is {:?}", double_first(strings));
    }
    

    总结

    了解了 Rust 中处理 Option 和 Result 同时存在的情况。

    附录

  • 相关阅读:
    javafx DragDropped file
    javafx style and cssFile
    javafx ComboBox Event and change cell color
    javafx clipboard
    javafx Cursor
    javafx DropShadow
    javafx checkbox
    javafx image button
    GNS3连接虚拟机
    cain使用教程
  • 原文地址:https://www.cnblogs.com/jiangbo44/p/15727694.html
Copyright © 2020-2023  润新知