2017-06-21 7 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

私はこれを支持した。 IMOでは、これは愚かな質問ではありません。なぜなら、 '? '演算子は少し不明瞭で、コード例を' main'に入れることができないという直感的ではないからです。私がよく覚えているなら、メインで 'Result'を使うことを許可するRFCがあります。 – 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関数でコンパイルしません。例を見ると、それらにはすべて「実行」ボタンがあります。これをクリックすると、プレーンに完全で無制限の例が開きます。

あなたは上記の使用してきた1本のコードに展開

:doesnの

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

あなたは(この場合はmain)関数にResultを伝播するコードを入れているので、このコードはコンパイルされません。返信はResultです。

+0

私は実行ボタンを見て、コードが異なっていたことに気付きました。私の最初の考えは、1つまたは他のバージョンが古くなったということでした。私はそれも '? 'とは関係があると思っていましたが、錆にまったく新しいものでした。 – alexbirkett

関連する問題