Rust中for循环使用模式匹配报错,如何添加Err分支?
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

