2017-08-16 43 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()仍然有效。