You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中for循环使用模式匹配报错,如何添加Err分支?

How to Handle Refutable Patterns in Rust for Loops

Ah, I’ve run into this exact issue before! The error message is telling you exactly what’s wrong: your for loop uses a refutable pattern (Ok(line)), which means there are elements in your iterator that won’t match it (the Err cases). Rust doesn’t allow this because it enforces that every element in the iterator is accounted for—no silent failures allowed.

Here are a few clean, idiomatic ways to fix this:

1. Use match to handle both cases explicitly

If you want to do something with the Err cases (like log an error or perform cleanup), using match is the most straightforward and explicit approach:

fn main() {
    struct EOF {};
    let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];
    
    for result in lines {
        match result {
            Ok(line) => println!("{}", line),
            Err(_eof) => {
                // Add custom error handling logic here
                eprintln!("Reached end of file!");
            }
        }
    }
}

2. Use if let to skip Err cases

If you just want to ignore errors and only process successful values, if let is more concise than a full match:

fn main() {
    struct EOF {};
    let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];
    
    for result in lines {
        if let Ok(line) = result {
            println!("{}", line);
        }
        // Err cases are silently skipped here
    }
}

3. Use iterator adapters for a functional style

For a more concise, functional approach, you can use filter_map to convert your iterator of Results into an iterator of only successful values:

fn main() {
    struct EOF {};
    let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];
    
    // res.ok() turns Result<T, E> into Option<T> (Some(T) for Ok, None for Err)
    // filter_map removes None values and unwraps Some
    for line in lines.into_iter().filter_map(|res| res.ok()) {
        println!("{}", line);
    }
}

All three methods will resolve the E0005 error. Choose the one that fits your needs: explicit error handling with match, simple skipping with if let, or a functional pipeline with iterator adapters.

内容的提问来源于stack exchange,提问作者Earth Engine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:01:08