关于 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)
相关推荐
球求了3 分钟前
C++:继承机制详解
开发语言·c++·学习
UestcXiye7 分钟前
Rust 学习笔记:函数和控制流
rust
张槊哲26 分钟前
函数的定义与使用(python)
开发语言·python
iuyou️32 分钟前
Spring Boot知识点详解
java·spring boot·后端
北辰浮光34 分钟前
[Mybatis-plus]
java·开发语言·mybatis
一弓虽44 分钟前
SpringBoot 学习
java·spring boot·后端·学习
姑苏洛言1 小时前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
光而不耀@lgy1 小时前
C++初登门槛
linux·开发语言·网络·c++·后端
lkbhua莱克瓦241 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
Mr__Miss1 小时前
面试踩过的坑
java·开发语言