Result
Result is similar to Option, but indicates the success or failure of an operation, each with a different enum variant. It is generic: Result<T, E> where T is used in the Ok variant and E appears in the Err variant.
use std::fs::File;
use std::io::Read;
fn main() {
let file: Result<File, std::io::Error> = File::open("diary.txt");
match file {
Ok(mut file) => {
let mut contents = String::new();
if let Ok(bytes) = file.read_to_string(&mut contents) {
println!("Dear diary: {contents} ({bytes} bytes)");
} else {
println!("Could not read file content");
}
}
Err(err) => {
println!("The diary could not be opened: {err}");
}
}
}
This slide should take about 5 minutes.
Optionと同様に、成功した値はResultの内部にあり、デベロッパーはそれを明示的に抽出する必要があります。これにより、エラーチェックが促進されます。エラーが発生してはならない場合は、unwrap()またはexpect()を呼び出すことができます。これもデベロッパーのインテントのシグナルです。Resultのドキュメントを読むことをすすめましょう。この講座では取り上げませんが、言及する価値があります。このドキュメントには、関数型プログラミングに役立つ便利なメソッドや関数が多数含まれています。Resultis the standard type to implement error handling as we will see on Day 4.