enum Result<T, E> {
Ok(T),
Err(E),
}
? 操作符
对比
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
和
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
和
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
?操作符用于返回Result<T,E>的表达式后面?操作符只能用于返回Result<T,E>的函数内部?操作符执行如下操作- 如果表达式返回
Ok则返回Ok内的值,并且继续执行代码 - 如果表达式返回
Err则直接返回整个函数,并调用Fromtrait 定义的from函数将错误转换为返回定义的错误类型
- 如果表达式返回