Rust中的问号运算符(?)是什么意思,它是如何工作的?
大家好!我最近开始学习Rust,遇到了一个奇怪的运算符——问号(?)。我在别人的代码中见过它,但无法理解它的作用。
下面是我找到的一个例子:
```rust
use std::fs::File;
use std::io::Read;
fn read_file(path: &str) -> Result {
let mut file = File::open(path)?; // 这里的`?`做了什么?
let mut contents = String::new();
file.read_to_string(&mut contents)?; // 还有这里?
Ok(contents)
}
```
我尝试不用这个运算符,用`match`写了类似的代码,结果变得非常冗长:
```rust
fn read_file_verbose(path: &str) -> Result {
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => return Err(e),
};
let mut contents = String::new();
match file.read_to_string(&mut contents) {
Ok(_) => {},
Err(e) => return Err(e),
};
Ok(contents)
}
```
由此可见,`?`替代了整整一