Search code examples
rustidiomsmap-function

How do I run a function on a Result or default to a value?


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?


Solution

  • You may be more familiar and comfortable with the map function from its common use in Iterators but using map to work with Results and Options 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());