2017-06-21 53 views
2

生鏽file examples不出現與Rust 1.18.0編譯。生鏽的文件示例不編譯

對於example

use std::fs::File; 
use std::io::prelude::*; 
fn main() { 
    let mut file = File::open("foo.txt")?; 
    let mut contents = String::new(); 
    file.read_to_string(&mut contents)?; 
    assert_eq!(contents, "Hello, world!"); 
} 

錯誤日誌:

rustc 1.18.0 (03fc9d622 2017-06-06) 
error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied 
--> <anon>:4:20 
    | 
4 |  let mut file = File::open("foo.txt")?; 
    |     ---------------------- 
    |     | 
    |     the trait `std::ops::Carrier` is not implemented for `()` 
    |     in this macro invocation 
    | 
    = note: required by `std::ops::Carrier::from_error` 

error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied 
--> <anon>:6:5 
    | 
6 |  file.read_to_string(&mut contents)?; 
    |  ----------------------------------- 
    |  | 
    |  the trait `std::ops::Carrier` is not implemented for `()` 
    |  in this macro invocation 
    | 
    = note: required by `std::ops::Carrier::from_error` 

error: aborting due to 2 previous errors 
+2

我upvoted。國際海事組織,這不是一個愚蠢的問題,因爲'?'操作符有點神祕,而且直覺上代碼示例不能放在'main'中。如果我記得,有一個RFC允許在主要中使用'Result'。 – Boiethios

+1

對我來說,錯誤日誌也是如此搞砸了。 – Stargateur

+0

相關答案:https://stackoverflow.com/a/43395610/1233251 –

回答

7

?是語法糖,檢查一個Result:如果結果是Err,它被返回彷彿。如果沒有錯誤(又名Ok),則該功能繼續。當你輸入:

fn main() { 
    use std::fs::File; 

    let _ = File::open("foo.txt")?; 
} 

這意味着:

fn main() { 
    use std::fs::File; 

    let _ = match File::open("foo.txt") { 
     Err(e) => return Err(e), 
     Ok(val) => val, 
    }; 
} 

然後你明白,現在,你不能在主要使用?,因爲主要的回報單元(),而不是Result。如果你想要這個東西的工作,你可以把它放在一個返回Result的功能和主要檢查:

fn my_stuff() -> std::io::Result<()> { 
    use std::fs::File; 
    use std::io::prelude::*; 

    let mut file = File::open("foo.txt")?; 
    let mut contents = String::new(); 
    file.read_to_string(&mut contents)?; 
    // do whatever you want with `contents` 
    Ok(()) 
} 


fn main() { 
    if let Err(_) = my_stuff() { 
     // manage your error 
    } 
} 

PS:有一個proposition,使工作?爲主。