2016-11-15 4 views
2

itemsstd::fs::read_dir()の関数から返されたio::Result<DirEntry>を処理しようとしています。私の関心は、私はまた、次の取り扱いio :: Result <DirEntry> Errで返品なし

let files = match fs::read_dir(&dir_path) { 
    Ok(items) => items, 
    Err(_) => return Err("Cannot read directory items".to_string()), 
    }; 

    for item in files { 
    let file: DirEntry; // I get compile error for use of possibly uninitialized `file` 
    match item { 
     Ok(de) => file = de, 
     Err(_) => println!("{:?} cannot be accessed", item), 
    }; 
    //do somthing with file 
    } 

たぶん例でmatchを使用せずにResultを処理するためのより良い方法があるがしようとしたときOk

let files = match fs::read_dir(&dir_path) { 
    Ok(items) => items, 
    //I actually want to leave function if there is an error here 
    Err(_) => return Err("Cannot read directory items".to_string()), 
}; 
for item in files { // item: io::Result<DirEntry> 
    match item { 
     Ok(de) => de,// how to get `de` out of this scope?? 
     //here I just want to print error and loop for next item 
     Err(_) => println!("{:?} cannot be accessed", item), 
    }; 
    //do something with `de` 
} 

Resultからmatchを適用するときDirEntryの値を取得する方法ですこのような? match外で変数を宣言

+0

それは私が行うことができます知っている ' – wimh

+0

、あなたがその範囲の外にそれを取得する必要はありませんように、あなたは' OK(デ)=> {/ *ドで何かをする* /}を行うことができます見えますこれは可能な限り入れ子にならないようにしたいと思います。 – MusuNaji

答えて

6

あなたの試みは、正しい軌道に乗っています。 Errブランチで実行の流れを次の反復に強制しないため、初期化されていない可能性のある変数についてエラーが発生しています。これを行うには、Errブランチにcontinueを追加します。その後、match式の結果を変数に直接代入することによって、変数をfiles変数と同じ方法で初期化することができます。

for item in files { 
    let file = match item { 
     Ok(de) => de, 
     Err(_) => { 
      println!("{:?} cannot be accessed", item); 
      continue; 
     } 
    }; 
    // do something with file 
    file; 
} 
+0

ご協力いただきありがとうございます。ここに「続ける」必要性があります。 – MusuNaji