文章目录
关于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 namedOurError
that we define. If we also defineimpl From<io::Error> for OurError
to construct an instance ofOurError
from anio::Error
, then the?
operator calls in the body ofread_username_from_file
will callfrom
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)