Rust5.1 Error Handling

Rust学习笔记

Rust编程语言入门教程课程笔记

参考教材: The Rust Programming Language (by Steve Klabnik and Carol Nichols, with contributions from the Rust Community)

Lecture 9: Error Handling

use std::error::Error;
use std::io::ErrorKind;
use std::fs::File;
use std::io::Read;
use std::net::IpAddr;
use std::io;fn main() -> Result<(), Box<dyn Error>> {//Box<dyn Error> means the function will return a type that implements the Error trait// Rust groups errors into two major categories: recoverable and unrecoverable errors.// For a recoverable error, such as a file not found error, it’s reasonable to report// the problem to the user and retry the operation. Unrecoverable errors are always// symptoms of bugs, like trying to access a location beyond the end of an array.// Recoverable errors are instances of the Result<T, E> enum, which has variants// Ok(T), representing success and containing a value, and Err(E), representing error// and containing an error value. The Result<T, E> enum is defined as part of the// standard library.// The panic! macro can be used to generate a panic and start unwinding its stack.// While unwinding, the runtime will take care of freeing all the resources owned by// the thread by calling the destructors of all its objects.let f = File::open("hello.txt");match f {Ok(file) => file,Err(error) => panic!("Problem opening the file: {:?}", error),};let _f = File::open("hello.txt").unwrap();//unwrap returns the Ok value inside the Ok variant//unwrap cannot define the type of the error so it will panic if it is Errlet _f = File::open("hello.txt").expect("Failed to open hello.txt");//expect is similar to unwrap but it allows us to choose the panic message//matching on different errorslet f = File::open("hello.txt");let _f = match f {Ok(file) => file,Err(error) => match error.kind() {ErrorKind::NotFound => match File::create("hello.txt") {Ok(fc) => fc,Err(error) => panic!("Problem creating the file: {:?}", error),},other_error => panic!("Problem opening the file: {:?}", other_error),},};let _f = File::open("hello.txt").unwrap_or_else(|error| {//unwrap_or_else takes a closureif error.kind() == ErrorKind::NotFound {File::create("hello.txt").unwrap_or_else(|error| {panic!("Problem creating the file: {:?}", error);})} else {panic!("Problem opening the file: {:?}", error);}});//propagating errorslet _ = read_username_from_file();//shortcut for propagating errors: the ? operatorlet _ = _read_username_from_file();//the ? operator can only be used in functions that return Result//translating errors from one type into another using From trait//when implementing the From trait, the standard library provides a generic//implementation of From<T> for any type T that implements the Into<U> trait//this is useful when we want to return a specific error type but the function//we are calling returns a generic error type//panic! vs Resultlet _home: IpAddr = "127.0.0.1".parse().expect("Hardcoded IP address should be valid");//create a custom type for the errorlet guess = Guess::new(99);//the constructor will check if the value is validprintln!("Guess value: {}", guess.value());//use ? in mainlet _greeting_file = File::open("hello.txt")?;Ok(()) //fn main() -> Result<(), Box<dyn Error>> 
}fn read_username_from_file() -> Result<String, io::Error> {let f = File::open("hello.txt");let mut f = match f {Ok(file) => file,Err(e) => return Err(e),//early return};let mut s = String::new();match f.read_to_string(&mut s) {Ok(_) => Ok(s),Err(e) => Err(e),//early return}
}pub struct Guess {value: i32,
}impl Guess {pub fn new(value: i32) -> Guess {if value < 1 || value > 100 {panic!("Guess value must be between 1 and 100, got {}.", value);}Guess { value }}pub fn value(&self) -> i32 {//we need to return a reference to the valueself.value}
}fn _read_username_from_file() -> Result<String, io::Error> {let mut f = File::open("hello.txt")?;//? can only be used in functions that return Resultlet mut s = String::new();f.read_to_string(&mut s)?;//? can only be used in functions that return ResultOk(s)
}   //? can be chained to simplify the code

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

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

相关文章

原型模式 rust和java的实现

文章目录 原型模式介绍优点缺点使用场景 实现java 实现rust 实现 rust代码仓库 原型模式 原型模式&#xff08;Prototype Pattern&#xff09;是用于创建重复的对象&#xff0c;同时又能保证性能。 这种模式是实现了一个原型接口&#xff0c;该接口用于创建当前对象的克隆。当…

POJ 3254 Corn Fields 状态压缩DP(铺砖问题)

一、题目大意 我们要在N * M的田地里种植玉米&#xff0c;有如下限制条件&#xff1a; 1、对已经种植了玉米的位置&#xff0c;它的四个相邻位置都无法继续种植玉米。 2、题目中有说一些块无论如何&#xff0c;都无法种植玉米。 求所有种植玉米的方案数&#xff08;不种植也…

JavaWeb Day08 Mybatis-入门

目录 ​编辑​编辑​编辑 一、快速入门程序 ①准备工作 ②引入Mybatis相关依赖&#xff0c;配置Mybatis ③编写SQL&#xff08;注解/XML&#xff09; ④单元测试 ⑤相关代码 1.pom.xml 2. application.properties 3.User.java 4. UserMapper.java 5.Test.java ⑥配置…

2390 高校实验室预约系统JSP【程序源码+文档+调试运行】

摘要 本文介绍了一个高校实验室预约系统的设计和实现。该系统包括管理员、教师和学生三种用户&#xff0c;具有基础数据管理、学生管理、教师管理、系统公告管理、实验室管理、实验室预约管理和系统管理等模块。通过数据库设计和界面设计&#xff0c;实现了用户友好的操作体验…

Halcon WPF 开发学习笔记(3):WPF+Halcon初步开发

文章目录 前言在MainWindow.xaml里面导入Halcon命名空间WPF简单调用Halcon创建矩形简单调用导出脚本函数 前言 本章会简单讲解如何调用Halcon组件和接口&#xff0c;因为我们是进行混合开发模式。即核心脚本在平台调试&#xff0c;辅助脚本C#直接调用。 在MainWindow.xaml里面…

如何安装Node.js? 创建Vue脚手架

1.进入Node.js官网&#xff0c;点击LTS版本进行下载 Node.js (nodejs.org)https://nodejs.org/en 2.然后一直【Next】即可 3.打开【cmd】,输入【node -v】注意node和-v中间的空格 查看已安装的Node.js的版本号&#xff0c;如果可以看到版本号&#xff0c;则安装成功 创建Vue脚手…

es 查询多个索引的文档

es 查询多个索引 第一种做法&#xff1a; 多个索引&#xff0c;用逗号隔开 GET /book_2020_09,book_2021_09/_search第二种做法&#xff1a; 可以用 * 模糊匹配。。比如 book* &#xff0c;表示查询所有 book开头的 索引。 GET /book*/_search GET /*book*/_search第二种做…

Python使用SQLAlchemy操作sqlite

Python使用SQLAlchemy操作sqlite sqllite1. SQLite的简介2. 在 Windows 上安装 SQLite3. 使用SQLite创建数据库3.1 命令行创建数据库3.2 navicat连接数据库 4.sqlite的数据类型存储类SQLite Affinity 类型Boolean 数据类型Date 与 Time 数据类型 5. 常用的sql语法**创建表(CREA…

dotnet core程序部署到ubuntu

visual studio2022编译好的dotnet core程序&#xff0c;打开“程序包管理器控制台”&#xff0c;打包发布dotnet core,使用命令 dotnet publish -c Release -r ubuntu.22.04-x64打包会生成ubuntu22.04-x64文件夹&#xff0c;将这个文件夹传到ubuntu服务器&#xff0c;切换到ubu…

Python的flask网页编程的GET和POST方法的区别

关于flask网页编程的GET及POST方法之间存在哪些区别问题&#xff0c;我们主要从以下六个关键点予以详细阐述&#xff1a; 首先需要明确的是&#xff0c;GET与POST两种不同类型的HTTP方法所采用的请求模式有所差别。其中&#xff0c;GET方法采用的是基于URL请求的机制&#xff…

微软和Red Hat合体:帮助企业更方便部署容器

早在2015年&#xff0c;微软就已经和Red Hat达成合作共同为企业市场开发基于云端的解决方案。时隔两年双方在企业市场的多个方面开展更紧密的合作&#xff0c;今天两家公司再次宣布帮助企业更方便地部署容器。 双方所开展的合作包括在微软Azure上部署Red Hat OpenShift&#xf…

竞赛 题目: 基于深度学习的疲劳驾驶检测 深度学习

文章目录 0 前言1 课题背景2 实现目标3 当前市面上疲劳驾驶检测的方法4 相关数据集5 基于头部姿态的驾驶疲劳检测5.1 如何确定疲劳状态5.2 算法步骤5.3 打瞌睡判断 6 基于CNN与SVM的疲劳检测方法6.1 网络结构6.2 疲劳图像分类训练6.3 训练结果 7 最后 0 前言 &#x1f525; 优…

手机开机入网流程 KPI接通率和掉线率

今天我们来学习手机开机入网流程是怎么样的。以及RRC连接和重建流程(和博主之前讲TCP三次握手&#xff0c;四次挥手原理很相似)是什么样的&#xff0c;还有天线的KPI指标都包括什么&#xff0c;是不是很期待啊~ 目录 手机开机入网流程 ATTACH/RRC连接建立过程 KPI接通率和掉…

安全通信网络(设备和技术注解)

网络安全等级保护相关标准参考《GB/T 22239-2019 网络安全等级保护基本要求》和《GB/T 28448-2019 网络安全等级保护测评要求》 密码应用安全性相关标准参考《GB/T 39786-2021 信息系统密码应用基本要求》和《GM/T 0115-2021 信息系统密码应用测评要求》 1网络架构 1.1保证网络…

hive和spark-sql中 日期和时间相关函数 测试对比

测试版本&#xff1a; hive 2.3.4 spark 3.1.1 hadoop 2.7.7 1、增加月份 add_months(timestamp date, int months)add_months(timestamp date, bigint months)Return type: timestampusage:add_months(now(),1) 2、增加日期 adddate(timestamp startdate, int days)…

爬虫项目(13):使用lxml抓取相亲信息

文章目录 书籍推荐完整代码效果书籍推荐 如果你对Python网络爬虫感兴趣,强烈推荐你阅读《Python网络爬虫入门到实战》。这本书详细介绍了Python网络爬虫的基础知识和高级技巧,是每位爬虫开发者的必读之作。详细介绍见👉: 《Python网络爬虫入门到实战》 书籍介绍 完整代码…

【C++】特殊类实现——设计一个类、不能被拷贝、只能在堆上创建对象、只能在栈上创建对象、不能被继承、单例模式、饿汉模式、懒汉模式

文章目录 C特殊类实现1.设计一个类、不能被拷贝2.设计一个类、只能在堆上创建对象3.设计一个类、只能在栈上创建对象4.设计一个类、不能被继承5.设计一个类&#xff0c;只能创建一个对象(单例模式)5.1饿汉模式5.2懒汉模式 C 特殊类实现 1.设计一个类、不能被拷贝 在C中&#x…

【微软技术栈】C#.NET 中使用依赖注入

本文内容 先决条件创建新的控制台应用程序添加接口添加默认实现添加需要 DI 的服务为 DI 注册服务结束语 本文介绍如何在 .NET 中使用依赖注入 (DI)。 借助 Microsoft 扩展&#xff0c;可通过添加服务并在 IServiceCollection 中配置这些服务来管理 DI。 IHost 接口会公开 IS…

模拟法——张三的零花钱(C#)

题目&#xff1a;张三的零花钱 不知道你有没有零花钱&#xff1f;你是如何管理⾃⼰的零花钱的&#xff1f;张三总爱乱花钱。每个⽉的⽉初妈妈给张三300元钱 &#xff0c;张三会预算这个⽉的花销&#xff0c;并且能做到实际的花销和预算相同。为了让张三学会对⾦钱的管理&#x…

node插件MongoDB(四)—— 库mongoose 操作文档使用(新增、删除、更新、查看文档)(二)

文章目录 前言&#xff08;1&#xff09;问题&#xff1a;安装的mongoose 库版本不应该过高导致的问题&#xff08;2&#xff09;重新安装低版本 一、插入文档1. 代码2. node终端效果3. 使用mongo.exe查询数据库的内容 二、删除文档1. 删除一条2. 批量删除3. 代码 三、修改文档…