rust - Dealing with Result within Iter -



rust - Dealing with Result within Iter -

let's assume function returns result:

class="lang-rust prettyprint-override">fn find(id: &id) -> result<item, itemerror> { // ... }

then using this:

class="lang-rust prettyprint-override">let parent_items: vec<item> = parent_ids.iter() .map(|id| find(id).unwrap()) .collect();

now question is, how handle case of failure within of map iterations?

i know utilize flat_map , in case error results ignored:

class="lang-rust prettyprint-override">let parent_items: vec<item> = parent_ids.iter() .flat_map(|id| find(id).into_iter()) .collect();

result's iterator has either 0 or 1 items depending on success state, , flat_map filter out if it's 0.

however, don't want ignore errors, want instead create whole code block stop , homecoming new error (based on error came within map, or forwards existing error).

how best handle in rust?

result implements fromiterator, can move result outside , iterators take care of rest (including stopping iteration if error found).

#[deriving(show)] struct item; type id = string; fn find(id: &id) -> result<item, string> { err(format!("not found: {}", id)) } fn main() { allow s = |s: &str| s.to_string(); allow ids = vec![s("1"), s("2"), s("3")]; allow items: result<vec<_>, _> = ids.iter().map(find).collect(); println!("result: {}", items); }

playpen.

rust

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -