首页 > 其他分享 >[Rust] Option vs Result

[Rust] Option vs Result

时间:2023-05-24 14:13:57浏览次数:48  
标签:Option Err people age vs Result println Rust

Option and Result are two very central enums in Rust, and they are used for error handling and for representing the absence of a value. Here is a breakdown of both:

  1. Option:

    • An Option represents an optional value: every Option is either Some and contains a value, or None, and does not.
    • Option is typically used when a function may succeed or fail, and you are only interested in the success case and don't care why the function failed.
    • Option is defined as follows:
    enum Option<T> {
        Some(T),
        None,
    }
    

    Here T is the type of the value to be stored in the Option.

  2. Result:

    • A Result is a type that represents either success (Ok) or failure (Err).
    • Unlike Option, Result does not assume failure is an "expected" or "uninteresting" case: it allows you to handle failures as well as successes.
    • Result is typically used when a function may succeed or fail, and you want to handle both cases.
    • Result is defined as follows:
    enum Result<T, E> {
        Ok(T),
        Err(E),
    }
    

    Here T is the type of the value to be returned in the success case (inside an Ok), and E is the type of the value to be returned in the failure case (inside an Err).

In general, you should use Result when you want to understand what the error was, and you should use Option when you don't care what the error was, only whether or not it occurred.

Some examples.

  1. Option<T>:

Suppose we have a function that finds a person's age based on their name in a predefined list. If the person is not in the list, it will return None.

use std::collections::HashMap;

fn find_age(people: &HashMap<String, u8>, name: &str) -> Option<u8> {
    people.get(name).cloned()
}

fn main() {
    let mut people = HashMap::new();
    people.insert("Alice".to_string(), 20);
    people.insert("Bob".to_string(), 30);

    match find_age(&people, "Alice") {
        Some(age) => println!("Alice is {} years old.", age),
        None => println!("I don't know Alice's age."),
    }

    match find_age(&people, "Charlie") {
        Some(age) => println!("Charlie is {} years old.", age),
        None => println!("I don't know Charlie's age."),
    }
}
  1. Result<T, E>:

Suppose we have a function that tries to divide two numbers. If the divisor is zero, it will return an error.

fn divide(numerator: f64, denominator: f64) -> Result<f64, &'static str> {
    if denominator == 0.0 {
        Err("Cannot divide by zero")
    } else {
        Ok(numerator / denominator)
    }
}

fn main() {
    match divide(10.0, 2.0) {
        Ok(result) => println!("10 divided by 2 is {}.", result),
        Err(err) => println!("Error: {}", err),
    }

    match divide(10.0, 0.0) {
        Ok(result) => println!("10 divided by 0 is {}.", result),
        Err(err) => println!("Error: {}", err),
    }
}

In the Option example, we only care about whether we found the age or not. In the Result example, we care about why the division failed, so we use a Result to get an error message in case of failure.

标签:Option,Err,people,age,vs,Result,println,Rust
From: https://www.cnblogs.com/Answer1215/p/17428117.html

相关文章

  • How to enable Vsync with Software Rendering in SDL [SOLVED]. 如何在SDL2下实现
    HowtoenableVsyncwithSoftwareRenderinginSDL[SOLVED].Hi,IjustfiguredoutthedirtywaytoenablevsyncwithsoftwarerenderingonSDL.Thiswasbotheringmeforaweeknow&I'veseenmanyquestionsonthenetwithoutanswer.ButIf......
  • Visual Studio Code (vscode)自定义用户代码段快速打出for循环等
    比如fori这样的快捷键就打不出代码块了自定义用户代码块的方法:工具栏>文件>首选项>用户代码片段  然后在弹出的搜索框中填写javascript.json有提示不用打全就行(会有javascript选中)  打开配置文件javascript.json这里面显示的就是编写代码块的例子"P......
  • Setup安装在VS设置
    Nuget安装InstallerProjects后 在需要做安装的项目文件里新建安装包项目,然后在ApplicationFolder右击Add文件,如下图winform的debug文件全部选定: ApplicationFolder再点Add“项目输出”: 右击新生成的主输出文件->Create Shortcut to主输出fromtest(Active)依赖......
  • 用rust 写一个jar包 class冲突检测工具
    Rust很适合写命令行工具,特别是使用clapcrate更加方便,这篇文章介绍使用rust写一个jar包class冲突检测的工具。项目地址:https://github.com/Aitozi/jar_conflict_detector首先jar包class冲突的现象是多个jar包中有同名的class,并且class的md5还不一样,那么就意味着该class存在多......
  • webpack-了解devServer中常用的选项
    devServer节点在webpack.config.js配置文件中,可以通过devServer节点对webpack-dev-server插件进行更多的配置,示例代码如下:devServer:{ open:ture,//初次打包完成后,自动打开浏览器 host:'127.0.0.1',//实时打包所使用的主机地址 port:80,//实时打包所使用的端口号}注意:凡是......
  • ps vs top:CPU占用率统计的两种不同方式
    如何计算CPU占用率?简单来说,进程的CPU占用率指的是CPU有多少时间花费在了运行进程上。在Linux系统里,进程运行的时间是以jiffies[1]统计的,通过计算jiffies*HZ,就可以得到进程消耗的CPU时间,再除以CPU的总时间,就可以得到进程的CPU占用率:jiffies*HZ/total_time。p......
  • vs git 分支缓存问题
    我们项目不停的开发,就会产生很多本地分支,但实际上git服务器上早就合并了,没有这么多分支,但VisualStudioGit分支本地一大堆,手动一个个删除太费时间。使用如下两条命令可以切换VisualStudioGit分支以git服务器上的分支为主,本地不做缓存。cmd或者gitbash直接执行gitconfig--g......
  • 文心一言 VS chatgpt (21)-- h264编码一帧数据的流程是怎样的?
    h264编码一帧数据的流程是怎样的?文心一言:H.264编码将一帧数据分成多个块,其中每个块可以单独进行编码。编码的过程包括预测、变换和量化等步骤。具体流程如下:1.帧内预测:对一帧视频进行编码,首先对当前块进行帧内预测。帧内预测使用已经编码的相邻块来预测当前块的值。2.帧间预......
  • 软硬件易混概念(二)同步vs异步
    1、硬件:同步时钟vs异步时钟同步时钟:同步时钟+当两个时钟间的相位是固定关系的,则可以称这两个时钟为同步时钟(synchronous+clock)。一般同源,如由同一个MMCMorPLL产生的两个时钟可以称为同步时钟。因此可以将主时钟和与之对应的衍生时钟约束成同一个时钟组。异步时钟:无法判定......
  • vscode配置远端服务器深度学习项目
    vscode配置远端服务器深度学习项目1.安装vscode官网地址:https://code.visualstudio.com/下载安装程序,运行安装即可2.连接服务器2.1安装相关插件需要安装Remote-SSH和RemoteDevelopment这两个插件2.2配置服务器连接插件安装完成后,在SSH一栏中点击OpenSSHCo......