关于 Rust 的 From 特性的尝试

文章目录

关于Rust的From特性的尝试

在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)
相关推荐
dialect_25 分钟前
KMP算法
开发语言·c++·算法
总要学点什么1 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
深蓝AI2 小时前
Python 3.13 的 Queue.shutdown:异步消费者终于能正常收工了
后端
武子康2 小时前
MultiNet6 空闲崩溃:`EXCVADDR=0x8` 后又出现 `CORRUPT HEAP`
人工智能·后端·agent
开开心心_Every3 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c3 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
吴卫斌3 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
武子康4 小时前
MultiNet7 每轮都 clean,ESP32-P4 内存为什么还在掉?
人工智能·后端·agent
超级架构师4 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
陈随易4 小时前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员