关于 Rust 的 From 特性的尝试

文章目录

关于RustFrom特性的尝试

The Rust Programming Language一书中,第 9.2 节Recoverable Errors with Result中有如下:

For example, we could change the read_username_from_file function in Listing 9-7 to return a custom error type named OurError that we define. If we also define impl From<io::Error> for OurError to construct an instance of OurError from an io::Error, then the ? operator calls in the body of read_username_from_file will call from and convert the error types without needing to add any more code to the function.

这里提到的From特性,并提到可以使用自定义的OurError,并为它实现impl From<io::Error> for OurError特性,我觉得我有时间可以尝试一下。

下面是我的尝试代码及输出:

rust 复制代码
#![allow(unused)]
use std::fs::File;
use std::io::{self, Read};

#[derive(Debug)]
struct OurError {
    desc: String,
}

impl From<io::Error> for OurError {
    fn from(value: io::Error) -> Self {
        OurError {
            desc: format!("From io::Error {} to OurError.", value),
        }
    }
}

fn read_username_from_file() -> Result<String, OurError> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}

fn main() {
    read_username_from_file().unwrap();
}

程序输出:

text 复制代码
thread 'main' panicked at src\main.rs:26:31:
called `Result::unwrap()` on an `Err` value: OurError { desc: "From io::Error 系统找不到指定的文件。 (os error 2) to OurError." }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\temp.exe` (exit code: 101)
相关推荐
掉头发的王富贵1 分钟前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
Cx330❀5 分钟前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
云间月13149 分钟前
飞算JavaAI智慧文旅场景实践:从景区管理到游客服务的全链路系统搭建
java·开发语言
盖世英雄酱5813610 分钟前
必须掌握的【InheritableThreadLocal】
java·后端
LovelyAqaurius11 分钟前
乐观锁及其实现方式详解
后端
绝无仅有14 分钟前
编写 Go 项目的 Dockerfile 文件及生成 Docker 镜像
后端·面试·github
tager24 分钟前
🍪 让你从此告别“Cookie去哪儿了?”
前端·javascript·后端
ERP老兵_冷溪虎山24 分钟前
GoLand 卡成幻灯片?Gopher 必藏的 vmoptions 调优表(续集:WebStorm 飞升后,轮到 Go 开发神器起飞)
后端·go
绝无仅有26 分钟前
使用 Docker 部署 Go 项目(Beego 框架)
后端·面试·github
leonkay26 分钟前
C# 现代化锁的最佳实践
后端