2017-08-16 39 views
1

我对try!?宏有极大的困难,我开始怀疑现实的结构。我举起straight from the rust-docs下面的例子,它仍然在我的脸上炸开。带问号的std文档示例不编译

代码:

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)

回答

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(()) 
    } 
} 

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

有一个RFC允许返回Resultmain()这是已经合并,虽然issue允许? S IN main()仍然有效。