2017-06-21 74 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,使工作?爲主。

4

他們編譯。它們只是不能編譯成main這樣的函數。如果你看例子,他們都有一個大的「運行」按鈕。點擊它並在圍欄上打開完整的,未刪節的示例。

你上面使用到的一個擴展到該代碼:

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

    fn foo() -> std::io::Result<()> { 
     let mut file = File::open("foo.txt")?; 
     let mut contents = String::new(); 
     file.read_to_string(&mut contents)?; 
     assert_eq!(contents, "Hello, world!"); 
     Ok(()) 
    } 
} 

代碼不編譯,因爲你已經把那傳播的Result成一個函數代碼(main在這種情況下),其沒有按不會返回Result

+0

我看到了運行按鈕,並指出代碼是不同的。我的第一個想法是,一個或其他版本過時了。我還懷疑它與'?'有關係,但卻是全新的鏽蝕,我不知道''是做什麼的。 – alexbirkett