关于 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)
相关推荐
PythonFun18 分钟前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
Death20022 分钟前
Qt 6 相比 Qt 5 的主要提升与更新
开发语言·c++·qt·交互·数据可视化
机器视觉知识推荐、就业指导24 分钟前
使用Qt实现实时数据动态绘制的折线图示例
开发语言·qt
快乐就好ya1 小时前
Java多线程
java·开发语言
CS_GaoMing2 小时前
Centos7 JDK 多版本管理与 Maven 构建问题和注意!
java·开发语言·maven·centos7·java多版本
艾伦~耶格尔2 小时前
Spring Boot 三层架构开发模式入门
java·spring boot·后端·架构·三层架构
man20172 小时前
基于spring boot的篮球论坛系统
java·spring boot·后端
2401_858120533 小时前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
转调3 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
Java探秘者3 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea