? 操作符与错误传播 ​

核心概念 ​

? 操作符是 Rust 中最常用的错误传播工具。它放在 Result 或 Option 值后面,作用是:如果值是 Ok(v) 或 Some(v),就把 v 取出来继续执行;如果值是 Err(e) 或 None,就立即从当前函数返回这个错误。? 还会自动调用 From::from 进行错误类型转换,所以即使底层错误类型和函数返回的错误类型不同,只要实现了对应的 From,? 就能自动处理。

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

// 没有 ? 操作符时的写法
fn read_file_verbose(path: &str) -> Result<String, io::Error> {
    let content = match fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => return Err(e),
    };
    Ok(content)
}

// 使用 ? 操作符的写法(完全等价)
fn read_file_concise(path: &str) -> Result<String, io::Error> {
    let content = fs::read_to_string(path)?;
    Ok(content)
}

// 更简洁:直接返回
fn read_file_shortest(path: &str) -> Result<String, io::Error> {
    fs::read_to_string(path)
}

fn main() {
    // 三种写法效果完全一样
    for reader in &[read_file_verbose, read_file_concise, read_file_shortest] {
        match reader("test.txt") {
            Ok(content) => println!("内容: {}", content),
            Err(e) => println!("错误: {}", e),
        }
    }
}

? 操作符的展开逻辑 ​

rust
use std::num::ParseIntError;
use std::fmt;

#[derive(Debug)]
enum MyError {
    Parse(ParseIntError),
    Validation(String),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MyError::Parse(e) => write!(f, "解析: {}", e),
            MyError::Validation(msg) => write!(f, "验证: {}", msg),
        }
    }
}

impl From<ParseIntError> for MyError {
    fn from(e: ParseIntError) -> Self {
        MyError::Parse(e)
    }
}

// ? 在 Result 上的展开等价于:
// match expr {
//     Ok(val) => val,
//     Err(e) => return Err(From::from(e)),
// }

fn parse_and_validate(s: &str) -> Result<u32, MyError> {
    // 步骤1:? 尝试取出 Ok 值
    //         如果是 Err(ParseIntError),自动调用 From::from 转为 MyError
    let n = s.parse::<u32>()?;

    // 步骤2:手动验证
    if n > 100 {
        return Err(MyError::Validation(format!("{} 超过上限 100", n)));
    }

    Ok(n)
}

fn main() {
    for input in &["42", "abc", "999"] {
        match parse_and_validate(input) {
            Ok(n) => println!("'{}' → {}", input, n),
            Err(e) => println!("'{}' → 错误: {}", input, e),
        }
    }
}

链式 ? 操作符 ​

? 可以连续使用,每一步失败都会立即返回错误。

rust
use std::io;
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum ConfigError {
    Io(io::Error),
    Parse(ParseIntError),
    Missing(String),
    Invalid(String),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::Io(e) => write!(f, "IO: {}", e),
            ConfigError::Parse(e) => write!(f, "解析: {}", e),
            ConfigError::Missing(key) => write!(f, "缺少配置: {}", key),
            ConfigError::Invalid(msg) => write!(f, "无效: {}", msg),
        }
    }
}

impl From<io::Error> for ConfigError {
    fn from(e: io::Error) -> Self { ConfigError::Io(e) }
}

impl From<ParseIntError> for ConfigError {
    fn from(e: ParseIntError) -> Self { ConfigError::Parse(e) }
}

#[derive(Debug)]
struct ServerConfig {
    host: String,
    port: u16,
    workers: u32,
}

fn find_value<'a>(content: &'a str, key: &str) -> Result<&'a str, ConfigError> {
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') || trimmed.is_empty() {
            continue;
        }
        if let Some(pos) = trimmed.find('=') {
            let k = trimmed[..pos].trim();
            if k == key {
                return Ok(trimmed[pos + 1..].trim());
            }
        }
    }
    Err(ConfigError::Missing(key.to_string()))
}

fn load_server_config(path: &str) -> Result<ServerConfig, ConfigError> {
    // 第一个 ?:文件读取可能失败
    let content = std::fs::read_to_string(path)?;

    // 第二个 ?:查找 host 可能失败
    let host = find_value(&content, "host")?;

    // 第三个 ?:查找 port 可能失败
    let port_str = find_value(&content, "port")?;

    // 第四个 ?:解析端口可能失败
    let port = port_str.parse::<u16>()?;

    // 第五个 ?:查找 workers 可能失败
    let workers_str = find_value(&content, "workers")?;

    // 第六个 ?:解析 workers 可能失败
    let workers = workers_str.parse::<u32>()?;

    // 手动验证
    if port == 0 {
        return Err(ConfigError::Invalid(String::from("端口不能为 0")));
    }

    Ok(ServerConfig {
        host: host.to_string(),
        port,
        workers,
    })
}

fn main() {
    match load_server_config("server.conf") {
        Ok(config) => println!("配置: {:?}", config),
        Err(e) => println!("加载失败: {}", e),
    }
}

? 用于 Option ​

? 也可以用在返回 Option 的函数中。

rust
// ? 在 Option 上的展开等价于:
// match expr {
//     Some(val) => val,
//     None => return None,
// }

fn first_even(numbers: &[i32]) -> Option<i32> {
    // find 返回 Option<&i32>
    // ? 在 None 时返回 None
    let even = numbers.iter().find(|&&n| n % 2 == 0)?;
    Some(*even)
}

fn get_nested_value(data: &Vec<Vec<i32>>, row: usize, col: usize) -> Option<i32> {
    // 第一个 ?:行可能不存在
    let row_data = data.get(row)?;
    // 第二个 ?:列可能不存在
    let value = row_data.get(col)?;
    Some(*value)
}

// 链式 Option 操作
fn parse_header(header: &str) -> Option<(String, String)> {
    let colon_pos = header.find(':')?;    // 没有冒号返回 None
    let key = header.get(..colon_pos)?;   // 获取键
    let value = header.get(colon_pos + 1..)?; // 获取值

    let key = key.trim();
    let value = value.trim();

    if key.is_empty() {
        return None;
    }

    Some((key.to_string(), value.to_string()))
}

fn main() {
    // Option 上的 ?
    let nums = vec![1, 3, 4, 7, 8];
    println!("第一个偶数: {:?}", first_even(&nums));
    println!("空列表: {:?}", first_even(&[]));

    let data = vec![vec![1, 2, 3], vec![4, 5, 6]];
    println!("data[0][1]: {:?}", get_nested_value(&data, 0, 1));
    println!("data[5][0]: {:?}", get_nested_value(&data, 5, 0));

    // 解析 header
    let headers = vec![
        "Content-Type: application/json",
        "Authorization: Bearer token123",
        "InvalidHeader",
        ": empty_key",
    ];
    for h in &headers {
        match parse_header(h) {
            Some((k, v)) => println!("  {} → {}", k, v),
            None => println!("  '{}' → 解析失败", h),
        }
    }
}

? 在 main 函数中 ​

rust
use std::error::Error;

// main 函数可以返回 Result
// 错误会自动通过 Debug 格式打印
fn main() -> Result<(), Box<dyn Error>> {
    let numbers = vec!["42", "17", "8"];

    let mut sum = 0;
    for s in &numbers {
        let n: i32 = s.parse()?;  // 失败时 main 返回错误
        sum += n;
    }

    println!("总和: {}", sum);
    Ok(())
}

? 不能混用 Result 和 Option ​

rust
// ? 用于 Result 的函数不能直接在 Option 上用 ?
// 反过来也一样

fn process() -> Result<String, String> {
    let items = vec!["hello", "world"];

    // 错误写法:Option 上的 ? 不能用在返回 Result 的函数中
    // let first = items.first()?;  // 编译错误

    // 正确写法1:用 ok_or 将 Option 转为 Result
    let first = items.first().ok_or("列表为空")?;

    // 正确写法2:用 ok_or_else 惰性生成错误
    let last = items.last().ok_or_else(|| String::from("列表为空"))?;

    Ok(format!("first={}, last={}", first, last))
}

fn lookup() -> Option<String> {
    let data: Result<String, String> = Ok(String::from("hello"));

    // 错误写法:Result 上的 ? 不能用在返回 Option 的函数中
    // let val = data?;  // 编译错误

    // 正确写法:用 ok() 将 Result 转为 Option
    let val = data.ok()?;

    Some(val)
}

fn main() {
    println!("process: {:?}", process());
    println!("lookup: {:?}", lookup());
}

基本示例 ​

用 ? 操作符构建一个多步骤的数据导入流程:

rust
use std::collections::HashMap;
use std::fmt;

#[derive(Debug)]
enum ImportError {
    EmptyInput,
    InvalidHeader(String),
    InvalidRow { line: usize, reason: String },
    DuplicateId(u32),
    ParseInt { line: usize, field: String, value: String },
    ParseFloat { line: usize, field: String, value: String },
}

impl fmt::Display for ImportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ImportError::EmptyInput => write!(f, "输入数据为空"),
            ImportError::InvalidHeader(h) => write!(f, "无效的表头: '{}'", h),
            ImportError::InvalidRow { line, reason } => {
                write!(f, "第{}行无效: {}", line, reason)
            }
            ImportError::DuplicateId(id) => write!(f, "重复的 ID: {}", id),
            ImportError::ParseInt { line, field, value } => {
                write!(f, "第{}行 '{}' 列 '{}' 不是整数", line, field, value)
            }
            ImportError::ParseFloat { line, field, value } => {
                write!(f, "第{}行 '{}' 列 '{}' 不是数字", line, field, value)
            }
        }
    }
}

#[derive(Debug)]
struct Product {
    id: u32,
    name: String,
    price: f64,
    quantity: u32,
}

// 解析表头
fn parse_header(line: &str) -> Result<Vec<String>, ImportError> {
    let fields: Vec<String> = line.split(',')
        .map(|s| s.trim().to_lowercase())
        .collect();

    // 检查必要字段
    let required = ["id", "name", "price", "quantity"];
    for req in &required {
        if !fields.iter().any(|f| f == req) {
            return Err(ImportError::InvalidHeader(
                format!("缺少必要字段 '{}'", req)
            ));
        }
    }

    Ok(fields)
}

// 解析数据行
fn parse_row(
    line_num: usize,
    line: &str,
    headers: &[String],
) -> Result<Product, ImportError> {
    let values: Vec<&str> = line.split(',').map(|s| s.trim()).collect();

    if values.len() != headers.len() {
        return Err(ImportError::InvalidRow {
            line: line_num,
            reason: format!("列数 {} 与表头 {} 不匹配", values.len(), headers.len()),
        });
    }

    // 建立字段名到值的映射
    let field_map: HashMap<&str, &str> = headers.iter()
        .map(|h| h.as_str())
        .zip(values.iter().copied())
        .collect();

    // 用 ? 逐步解析每个字段
    let id_str = field_map.get("id")
        .ok_or_else(|| ImportError::InvalidRow {
            line: line_num,
            reason: String::from("缺少 id"),
        })?;

    let id = id_str.parse::<u32>().map_err(|_| ImportError::ParseInt {
        line: line_num,
        field: String::from("id"),
        value: id_str.to_string(),
    })?;

    let name = field_map.get("name")
        .ok_or_else(|| ImportError::InvalidRow {
            line: line_num,
            reason: String::from("缺少 name"),
        })?
        .to_string();

    let price_str = field_map.get("price")
        .ok_or_else(|| ImportError::InvalidRow {
            line: line_num,
            reason: String::from("缺少 price"),
        })?;

    let price = price_str.parse::<f64>().map_err(|_| ImportError::ParseFloat {
        line: line_num,
        field: String::from("price"),
        value: price_str.to_string(),
    })?;

    let qty_str = field_map.get("quantity")
        .ok_or_else(|| ImportError::InvalidRow {
            line: line_num,
            reason: String::from("缺少 quantity"),
        })?;

    let quantity = qty_str.parse::<u32>().map_err(|_| ImportError::ParseInt {
        line: line_num,
        field: String::from("quantity"),
        value: qty_str.to_string(),
    })?;

    Ok(Product { id, name, price, quantity })
}

// 导入完整 CSV 数据
fn import_csv(input: &str) -> Result<Vec<Product>, ImportError> {
    let mut lines = input.lines();

    // 第一行是表头
    let header_line = lines.next()
        .ok_or(ImportError::EmptyInput)?;
    let headers = parse_header(header_line)?;

    let mut products = Vec::new();
    let mut seen_ids = HashMap::new();

    for (i, line) in lines.enumerate() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let line_num = i + 2;  // 第2行开始(第1行是表头)
        let product = parse_row(line_num, trimmed, &headers)?;

        // 检查重复 ID
        if seen_ids.contains_key(&product.id) {
            return Err(ImportError::DuplicateId(product.id));
        }
        seen_ids.insert(product.id, line_num);

        products.push(product);
    }

    if products.is_empty() {
        return Err(ImportError::EmptyInput);
    }

    Ok(products)
}

fn main() {
    // 正确的 CSV 数据
    let good_csv = "\
id, name, price, quantity
1, 键盘, 299.0, 50
2, 鼠标, 99.5, 100
3, 显示器, 2999.0, 20";

    match import_csv(good_csv) {
        Ok(products) => {
            println!("导入成功: {} 条记录", products.len());
            for p in &products {
                println!("  #{}: {} ¥{:.0} x{}", p.id, p.name, p.price, p.quantity);
            }
            let total: f64 = products.iter()
                .map(|p| p.price * p.quantity as f64)
                .sum();
            println!("  总价值: ¥{:.0}", total);
        }
        Err(e) => println!("导入失败: {}", e),
    }

    println!();

    // 有错误的数据
    let bad_csv = "\
id, name, price, quantity
1, 键盘, 299.0, 50
2, 鼠标, abc, 100";

    match import_csv(bad_csv) {
        Ok(products) => println!("导入成功: {} 条", products.len()),
        Err(e) => println!("导入失败: {}", e),
    }

    // 重复 ID
    let dup_csv = "\
id, name, price, quantity
1, 键盘, 299.0, 50
1, 鼠标, 99.0, 100";

    match import_csv(dup_csv) {
        Ok(products) => println!("导入成功: {} 条", products.len()),
        Err(e) => println!("导入失败: {}", e),
    }
}

常见问题 ​

问题一:? 可以用在任何函数中吗?

不可以。? 只能用在返回 Result 或 Option 的函数中。在返回 () 的普通函数里用 ? 会编译错误。main 函数可以返回 Result<(), E> 来支持 ?。

问题二:? 和 unwrap 有什么区别?

? 在错误时返回错误给调用者,让调用者决定如何处理。unwrap 在错误时直接 panic,程序崩溃。? 是安全的错误传播,unwrap 是不安全的强制取值。

特性? 操作符unwrap
错误时行为返回 Errpanic
类型转换自动 From无
安全性安全不安全
需要的返回类型Result/Option任何

问题三:? 可以在闭包中使用吗?

可以,但 ? 只会从闭包返回,不会从外层函数返回。闭包的返回类型也必须是 Result 或 Option。

问题四:? 用于 Option 时返回什么?

返回 None。和 Result 不同的是,Option 上的 ? 不会做任何转换,遇到 None 就直接返回 None。

适用场景 ​

  • 多步操作:每步都可能失败,连续使用 ? 传播
  • 错误传播:将底层错误传递给上层调用者
  • 简化代码:替代繁琐的 match 错误处理
  • main 函数:返回 Result 配合 ? 使用

注意事项 ​

  • ? 只能用在返回 Result 或 Option 的函数中
  • ? 会自动调用 From::from 进行错误类型转换
  • ? 用于 Result 和 Option 不能混用
  • Option 转 Result 用 .ok_or() 或 .ok_or_else()
  • Result 转 Option 用 .ok()
  • ? 在闭包中只从闭包返回,不从外层函数返回
  • main 函数返回 Result 时,错误通过 Debug 格式打印

总结 ​

? 操作符是 Rust 中最重要的错误传播工具,将 match + return Err 的模式简化为一个符号。它在 Ok/Some 时取出值继续执行,在 Err/None 时立即返回。? 会自动调用 From::from 进行错误类型转换,配合为自定义错误实现的 From trait,让多步操作的错误传播代码变得极度简洁。但 ? 只能用在返回 Result 或 Option 的函数中,且两者不能混用。Option 和 Result 之间的转换通过 ok_or、ok 等方法完成。? 和 From trait 构成了 Rust 错误传播的核心机制。