We wish to run a function on a Result
or if the result is actually an error have a default value. Something like:
let is_dir = entry.file_type().is_dir() || false
// ^--- file_type() returns a Result
// ^--- default to false if Result is an IOError
At the moment, we're doing it with:
let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
But that seems horribly confusing, to run a map
on a single item result. Is there a better way of doing it?
You may be more familiar and comfortable with the map
function from its common use in Iterator
s but using map
to work with Result
s and Option
s is also considered idiomatic in Rust. If you'd like to make your code more concise you can use map_or
like so:
let is_dir = entry.file_type().map_or(false, |t| t.is_dir());