Result
Result 和 Option 類似,但會指出作業成功或失敗,且各自都有不同的型別。雖然和運算式練習中定義的 Res 很像,但這屬於泛型,也就是 Result<T, E>,其中 T 用於 Ok 變體,而 E 則會出現在 Err 變數中。
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 10 minutes.
- 就跟使用
Option一樣,成功的值會在 Result 內部,這會強制開發人員明確擷取該值,進而有利於檢查錯誤。在應該絕對不會發生錯誤的情況下,可以呼叫unwrap()或expect(),這也是開發人員意圖的訊號。 Resultdocumentation is a recommended read. Not during the course, but it is worth mentioning. It contains a lot of convenience methods and functions that help functional-style programming.Result是實作錯誤處理的標準型別,我們將在第 3 天的課程中介紹。