关于 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 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
怒放吧德德1 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆3 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
开心就好20254 小时前
UniApp开发应用多平台上架全流程:H5小程序iOS和Android
后端·ios
悟空码字5 小时前
告别“屎山代码”:AI 代码整洁器让老项目重获新生
后端·aigc·ai编程
小码哥_常5 小时前
大厂不宠@Transactional,背后藏着啥秘密?
后端
奋斗小强5 小时前
内存危机突围战:从原理辨析到线上实战,彻底搞懂 OOM 与内存泄漏
后端
小码哥_常5 小时前
Spring Boot接口防抖秘籍:告别“手抖”,守护数据一致性
后端
心之语歌6 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
None3216 小时前
【NestJs】基于Redlock装饰器分布式锁设计与实现
后端·node.js