关于 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)
相关推荐
lly202406几秒前
数据访问对象模式(Data Access Object Pattern)
开发语言
该用户已不存在3 分钟前
这6个网站一旦知道就离不开了
前端·后端·github
LSTM976 分钟前
使用 Python 将 PDF 转成 Excel:高效数据提取的自动化之道
后端
英伦传奇7 分钟前
Docker部署MySQL 8.0
后端
Ai行者心易7 分钟前
10天!前端用coze,后端用Trae IDE+Claude Code从0开始构建到平台上线
前端·后端
00后程序员8 分钟前
开发代码的前端工具全流程分享 从编辑、构建到调试的实战经验
后端
std8602111 分钟前
Rust 与 Python – 这是未来的语言吗?
开发语言·python·rust
用户685453759776915 分钟前
🎴 Card Table & Remember Set:GC的超级加速器!
后端
Json_17 分钟前
学习springBoot框架-开发一个酒店管理系统,熟悉springboot框架语法~
java·spring boot·后端
用户685453759776920 分钟前
⚡ ZGC:Java界的"闪电侠"!但是...这些坑你得注意!🕳️
后端