1

我在宏观方面遇到了极大的困难,try!以至于?我开始质疑现实的结构。我直接从 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 的最新稳定版本

4

1 回答 1

1

这些示例目前预计将在返回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(())
    }
}

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

有一个RFC允许Resultmain()已经合并的地方返回,尽管允许s in的问题仍然存在。?main()

于 2017-08-16T08:50:15.380 回答