Rust- 错误处理

Rust approaches error handling with the aim of being explicit about possible error conditions. It separates the concerns of “normal” return values and “error” return values by using a specific set of types for each concern. Rust’s primary tools for expressing these concepts are the Result and Option types, along with the unwrap method.

  1. The Result type: This is an enum that represents either successful (Ok) or unsuccessful (Err) computation. Functions that can fail generally return a Result variant.

    Here’s a simple example:

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

    In this case, if you try to divide by zero, the function will return an error wrapped in the Err variant. Otherwise, it will return the division result wrapped in the Ok variant.

  2. The Option type: This is another enum that represents a value that could be something (Some) or nothing (None). It’s often used when you have a situation where a value could be absent or present.

    For example:

    fn find_word_starting_with<'a, 'b>(sentence: &'a str, initial: &'b str) -> Option<&'a str> {for word in sentence.split_whitespace() {if word.starts_with(initial) {return Some(word);}}None
    }
    

    This function tries to find a word starting with a specific string in a sentence. If it finds such a word, it returns Some(word), otherwise, it returns None.

  3. The unwrap method: Both Option and Result types have an unwrap method, which is used to get the value out. If the instance of Option is a Some variant, unwrap will return the value inside the Some. If the instance is a None, unwrap will panic.

    Similarly, for Result, if the instance is an Ok, unwrap will return the value inside the Ok. If the instance is an Err, unwrap will panic.

    let maybe_number: Option<i32> = Some(42);
    println!("{}", maybe_number.unwrap()); // Prints 42let definitely_not_a_number: Option<i32> = None;
    println!("{}", definitely_not_a_number.unwrap()); // This will panic
    

    It’s generally advised to avoid using unwrap in most situations, as it can lead to your program crashing. Instead, you should handle errors appropriately using pattern matching or methods like unwrap_or, unwrap_or_else, expect, etc., which allow you to provide alternative values or actions in case of an error.

  4. The ? operator: This is a convenient way to propagate errors upwards in the call stack. When you use ? on a Result value, it does pretty much the same as a match expression would do: if the value is Ok, it unwraps it; if it’s Err, it returns it from the current function. This allows for more concise error handling.

fn main() {match foo() {Ok(_) => println!("Success"),Err(e) => println!("Error: {}", e),}
}fn foo() -> Result<(), &'static str> {bar()?;Ok(())
}fn bar() -> Result<(), &'static str> {Err("Some error")
}

In the foo function, bar()? will return the error from bar, thus ending the foo function early.

These are the basic building blocks of error handling in Rust. Rust also provides advanced features like creating your own error types, using the From trait for flexible error conversions, etc., but those are more advanced topics.

use std::fs::File;fn main() {panic!("出错了");println!("Hello Rust");// panic 程序立即退出,退出的时候调用者抛出退出原因。// 数组越界let v = vec!["Rust", "Programming", "Language"];println!("{}", v[5]); // thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 5'// 打开文件出错let f = File::open("abc.txt");println!("{:?}", f); // Err(Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。" })// unwrap expectlet result = is_even(6).unwrap();println!("结果{}", result);let result = is_even(11).unwrap();println!("结果{}", result);// unwrap()是Result<T, E>的方法,实例上调用此方法时,如果是Ok,就返回Ok中的对象// 如果是Err枚举,在运行时会panic// expect()接收msg::&str作为参数,可以自定义报错信息。
}fn is_even(no: i32) -> Result<bool, String> {return if no % 2 == 0 {Ok(true)} else {Err("输入的值不是偶数".to_string())};
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/15555.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OpenHarmony开源鸿蒙学习入门 - 基于3.2Release 应用开发环境安装

OpenHarmony开源鸿蒙学习入门 - 基于3.2Release 应用开发环境安装 基于目前官方master主支&#xff0c;最新文档版本3.2Release&#xff0c;更新应用开发环境安装文档。 一、安装IDE&#xff1a; 1.IDE安装的系统要求 2.IDE下载官网链接&#xff08;IDE下载链接&#xff09; …

Modbus tcp转ETHERCAT在Modbus软件中的配置方法

Modbus tcp和ETHERCAT是两种不同的协议&#xff0c;这给工业生产带来了很大的麻烦&#xff0c;因为这两种设备之间无法通讯。但是&#xff0c;捷米JM-ECT-TCP网关的出现&#xff0c;却为这个难题提供了解决方案。 JM-ECT-TCP网关能够连接到Modbus tcp总线和ETHERCAT总线中&…

C++ 关于大端小端的简析

大端及小端的简析 序言环境概念理解可能有问题的地方一般情况下需要注意的大小端情况关于大小端相关的实用函数/代码判断自身大小端的代码大小端转换函数 序言 我记得我已经查过4次了&#xff0c;最近回想一下发现我竟然又忘了&#xff01;所以特以此文来记录一下。 环境 Qt…

网络面试合集

传输层的数据结构是什么&#xff1f; 就是在问他的协议格式&#xff1a;UDP&TCP 2.1.1三次握手 通信前&#xff0c;要先建立连接&#xff0c;确保双方都是在线&#xff0c;具有数据收发的能力。 2.1.2四次挥手 通信结束后&#xff0c;会有一个断开连接的过程&#xff0…

Qsys介绍

文章目录 前言一、为什么需要Qsys1、简化了系统的设计流程2、Qsys涉及的技术 二、Qsys真身1、一种系统集成工具2、何为Nios II1、内核架构2、Nios II选型 三、Qsys设计涉及到的软件&工具四、总结五、参考资料 前言 Qsys是Altera下的一个系统集成工具&#xff0c;可用于搭建…

APP自动化测试-Python+Appium+Pytest+Allure框架实战封装(详细)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 pytest只是单独的…

JVM入门篇-JVM的概念与学习路线

JVM入门篇-JVM的概念与学习路线 什么是 JVM 定义 Java Virtual Machine - java 程序的运行环境&#xff08;java 二进制字节码的运行环境&#xff09; 好处 一次编写&#xff0c;到处运行自动内存管理&#xff0c;垃圾回收功能数组下标越界检查多态 比较 jvm jre jdk 常…

MQTT工具类

项目中用到的MQTT物联网通信协议&#xff0c;记录一下工具类&#xff0c;方便翻阅 用到的依赖&#xff1a; <!--mqtt--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-integration</artifactId&g…

单片机第一季:零基础12——I2C和EEPROM

目录 1&#xff0c;EEPROM 2&#xff0c;I2C 2.1&#xff0c;I2C物理层 2.2&#xff0c;I2C协议层 3&#xff0c;AT24C02介绍 4&#xff0c;代码 1&#xff0c;EEPROM 为什么需要EEPROM&#xff1f; 单片机内部的ROM只能在程序下载时进行擦除和改写&#xff0c;但是…

护眼灯全光谱和减蓝光哪个好?推荐五款好用护眼台灯

如今&#xff0c;面临视力下降的问题越来越重视&#xff0c;护眼灯越来越成为人们日常生活中不可或缺的一部分&#xff0c;特别是在工作和学习中使用电脑、手机等电子设备时间较长的人群中。对于护眼灯来说&#xff0c;全光谱和减蓝光都是其主要功能之一&#xff0c;那么哪一种…

aws中opensearch 日志通(Centralized Logging with OpenSearch)2.0(一)

aws日志通2.0 实现全面的日志管理和分析功能 一体化日志摄取 &#xff1a;把aws服务器日志和应用日志传输到opensearch域中无代码日志处理 &#xff1a;在网页控制台中就可以实现数据处理开箱即用 &#xff1a;提供可视化模版&#xff08;nginx、HTTP server &#xff09; 架构…

mysql 主从同步排查和处理 Slave_IO、Slave_SQL

目录 查看主从是否同步 详解Slave_IO、Slave_SQL 判断主从完全同步 各个 Log_File 和 Log_Pos的关系 修复命令 查看主从是否同步 show slave status; Slave_IO_Running、Slave_SQL_Running&#xff0c;这两个值是Yes表示正常&#xff0c;No是异常 使用竖排显示&#xf…

使用 CSS 自定义属性

我们常见的网站日夜间模式的变化&#xff0c;其实用到了 css 自定义属性。 CSS 自定义属性&#xff08;也称为 CSS 变量&#xff09;是一种在 CSS 中预定义和使用的变量。它们提供了一种简洁和灵活的方式来通过多个 CSS 规则共享相同的值&#xff0c;使得样式更易于维护和修改。…

小研究 - 主动式微服务细粒度弹性缩放算法研究(一)

微服务架构已成为云数据中心的基本服务架构。但目前关于微服务系统弹性缩放的研究大多是基于服务或实例级别的水平缩放&#xff0c;忽略了能够充分利用单台服务器资源的细粒度垂直缩放&#xff0c;从而导致资源浪费。为此&#xff0c;本文设计了主动式微服务细粒度弹性缩放算法…

windows端口占用

1.查看当前端口被哪个进程占用了&#xff08;进入到CMD中&#xff09; netstat -ano|findstr "8990"输出结果为&#xff1a; TCP 127.0.0.1:8990 0.0.0.0:0 LISTENING 2700 我们发现8990端口被2700进程占用了 2.基于进程号找进程名称 tasklist|findstr "2700&qu…

【LeetCode每日一题】——566.重塑矩阵

文章目录 一【题目类别】二【题目难度】三【题目编号】四【题目描述】五【题目示例】六【题目提示】七【解题思路】八【时间频度】九【代码实现】十【提交结果】 一【题目类别】 矩阵 二【题目难度】 简单 三【题目编号】 566.重塑矩阵 四【题目描述】 在 MATLAB 中&…

【leetcode】977. 有序数组的平方(easy)

给你一个按 非递减顺序 排序的整数数组 nums&#xff0c;返回 每个数字的平方 组成的新数组&#xff0c;要求也按 非递减顺序 排序。 示例 1&#xff1a; 输入&#xff1a;nums [-4,-1,0,3,10] 输出&#xff1a;[0,1,9,16,100] 解释&#xff1a;平方后&#xff0c;数组变为 […

小红书运营推广方法分享

大家好&#xff0c;我是网媒智星&#xff0c;今天跟大家讨论一下小红书的运营推广方法&#xff0c;总结了七点经验分享给大家。 首先&#xff0c;让我们了解一下什么是热门文案。热门文案可从以下三个方面来定义&#xff1a; 1. 阅读量&#xff1a;如果一篇小红书的阅读量达到上…

【RabbitMQ】golang客户端教程1——HelloWorld

一、介绍 本教程假设RabbitMQ已安装并运行在本机上的标准端口&#xff08;5672&#xff09;。如果你使用不同的主机、端口或凭据&#xff0c;则需要调整连接设置。如果你未安装RabbitMQ&#xff0c;可以浏览我上一篇文章Linux系统服务器安装RabbitMQ RabbitMQ是一个消息代理&…

3,this指针、深拷贝浅拷贝、namespace的使用

3&#xff0c;this指针、深拷贝浅拷贝、namespace的使用 3.1this指针3.2深拷贝和浅拷贝3.3namespace的使用 3.1this指针 定义&#xff1a;当前类指向自己地址的常量指针 指针被const修饰&#xff0c;指针指向的内容不能修改 this指针-》类 对象 占不占用大小&#xff1f; this…