{"id":300,"hash":"0841e9a11805769ab439b5ca34fd8eacef86621381119bea9afa13e5fd042ed7","pattern":"How do I stop iteration and return an error when Iterator::map returns a Result::Err?","full_message":"I have a function that returns a Result:\n\nfn find(id: &Id) -> Result<Item, ItemError> {\n    // ...\n}\n\nThen another using it like this:\n\nlet parent_items: Vec<Item> = parent_ids.iter()\n    .map(|id| find(id).unwrap())\n    .collect();\n\nHow do I handle the case of failure inside any of the map iterations?\n\nI know I could use flat_map and in this case the error results would be ignored:\n\nlet parent_items: Vec<Item> = parent_ids.iter()\n    .flat_map(|id| find(id).into_iter())\n    .collect();\n\nResult's iterator has either 0 or 1 items depending on the success state, and flat_map will filter it out if it's 0.\n\nHowever, I don't want to ignore errors, I want to instead make the whole code block just stop and return a new error (based on the error that came up within the map, or just forward the existing error).\n\nHow do I best handle this in Rust?","ecosystem":"cargo","package_name":"rust-result","package_version":null,"solution":"Result implements FromIterator, so you can move the Result outside and iterators will take care of the rest (including stopping iteration if an error is found).\n\n#[derive(Debug)]\nstruct Item;\ntype Id = String;\n\nfn find(id: &Id) -> Result<Item, String> {\n    Err(format!(\"Not found: {:?}\", id))\n}\n\nfn main() {\n    let s = |s: &str| s.to_string();\n    let ids = vec![s(\"1\"), s(\"2\"), s(\"3\")];\n\n    let items: Result<Vec<_>, _> = ids.iter().map(find).collect();\n    println!(\"Result: {:?}\", items);\n}\n\nPlayground","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/26368288/how-do-i-stop-iteration-and-return-an-error-when-iteratormap-returns-a-result","votes":263,"created_at":"2026-04-19T04:41:47.322259+00:00","updated_at":"2026-04-19T04:52:27.230746+00:00"}