带有问号的标准文档示例无法编译

The std documentation examples with question marks don't compile

我在使用 try!? 宏时遇到了极大的困难,以至于我开始质疑现实的结构。我举了下面的例子straight from the rust-docs,它仍然在我面前爆炸。

代码:

pub use std::fs::File;
pub use std::io::prelude::*;

fn main() {
    let mut file: File = File::open("foo.txt")?;
    file.write_all(b"Hello, world!")?;
}

错误:

error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src/main.rs:6:23
|
6 |     let mut file: File = File::open("foo.txt")?;
|                          ----------------------
|                          |
|                          the trait `std::ops::Try` is not implemented for `()`
|                          in this macro invocation
|
= note: required by `std::ops::Try::from_error`

error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src/main.rs:7:2
|
7 |     file.write_all(b"Hello, world!")?;
|     ---------------------------------
|     |
|     the trait `std::ops::Try` is not implemented for `()`
|     in this macro invocation
|
= note: required by `std::ops::Try::from_error`

根据 rustup (1.19.0)

,我正在使用 Rust 的最新稳定版本

这些示例目前预计 运行 包装在返回 Result 的函数中;如果单击示例右上角的 运行,您将看到它扩展为:

fn main() {
    use std::fs::File;
    use std::io::prelude::*;

    fn foo() -> std::io::Result<()> {
        let mut file = File::create("foo.txt")?;
        file.write_all(b"Hello, world!")?;
        Ok(())
    }
}

这是因为返回 Result 的函数(如 File::createio::Write::write_all)在处理时应考虑到可能出现的错误(这在文档示例中尤为重要)。

有一个 RFC to allow returning Result from main() that was already merged, though the issue 允许 main() 中的 ? 仍然有效。