0

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?

2 Answers 2

5

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()); 
Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively, if you find the map unclear, you could use an if or match to be more explicit (and verbose):

let is_dir = if let Ok(file_type) = entry.file_type() { file_type.is_dir() } else { false }; 

or

let is_dir = match entry.file_type() { Ok(file_type) => file_type.is_dir(), _ => false, }; 

Not necessarily better or worse, but an option available to you :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.