Rust 程式設計影片教程對應講解內容-傳播錯誤

linghuyichong發表於2020-01-01

頭條地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
網易雲課堂地址:https://study.163.com/course/introduction....

1、當編寫一個函式,但是該函式可能會失敗,此時除了在函式中處理錯誤外,還可以將錯誤傳給呼叫者,讓呼叫者決定如何處理,這被稱為傳播錯誤。
例子:

use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

2、傳播錯誤的簡寫方式,提倡的方式

use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

3、更進一步的簡寫

use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}
//說明1:rust提供了fs::read_to_string函式
use std::io;
use std::fs;
fn read_username_from_file() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}
//說明2:?運算子被用於返回Result的函式,如果不是返回Result的函式,用?會報錯

3、什麼時候用panic!,什麼時候用Result
(1)示例、程式碼原型和測試適合panic,也就是直接panic!、unwrap、expect的方式
(2)實際專案中應該多使用Result

4、Option和Result
Option是可能存在空值,而Result是可能存在錯誤

本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章