If you have an iterator of Result
s, you can collect and unwrap all values into a Vec
on success or return the first Err
on failure:
let content_of_files = file_names.iter
.map
.?;
The type hint in .collect
makes it construct a Result
instead of just a Vec
. If it was .collect::<Vec<_>>()
instead, it would make a Vec<Result<String, Error>>
of mixed Ok
and Err
values.
.collect
can make anything that implements FromIterator
, and there are implementations of FromIterator
for Result
, Option
, and even ()
.
See it in the Rust Playground.