Day 1:Result 與 ? 運算子

學習目標

  • 理解 Result
  • 學會用 ? 傳播錯誤
  • 用 From 自動轉換錯誤型別

今日重點

基本錯誤處理

use std::fs::File;
use std::io::{self, Read};

fn read_file(path: &str) -> Result<String, io::Error> {
    let mut file = File::open(path)?;      // ? 遇 Err 直接回傳
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;   // ? 遇 Err 直接回傳
    Ok(contents)
}

? 是什麼?

? 展開成:若是 Ok(v) → 取 v;若是 Err(e) → 立即 return Err(e.into()),把錯誤傳給呼叫端。

? 簡化

fn read_file_short(path: &str) -> Result<String, io::Error> {
    let mut contents = String::new();
    File::open(path)?.read_to_string(&mut contents)?;
    Ok(contents)
}

? 運算子只能在回傳 Result / Option / 相容型別的函式裡用。

一般的 fn main() 不能直接 ?,除非主函式回傳 Result

練習

use std::fs;
use std::io;

fn read_lines(path: &str) -> io::Result<Vec<String>> {
    let content = fs::read_to_string(path)?;   // ? 傳播
    Ok(content.lines().map(|l| l.to_string()).collect())
}
1. 寫一個用 ? 讀檔並回傳行數的函式。 2. 在 main 裡改用一個回傳 Result 的 main 或 match 處理。

自我檢查

  • 理解 Result
  • 知道 ? 的展開行為
  • 知道 ? 的使用限制(需回傳相容型別)

深入連結

  • The Book 第 9 章「A Shortcut for Propagating Errors: the ? Operator」