Clippy doesn't like method calls in 'unwrap_or'

If I try to write this

fn main() {
    let foo = return_string().unwrap_or("bar".to_string());
fn return_string() -> Option<String> {

Clippy complains with this message

Arguments passed to  `unwrap_or`  are eagerly evaluated; 
if you are passing the result of a function call, 
it is recommended to use [ `unwrap_or_else` ](#), 
which is lazily evaluated.

I don't really see a way to get around things of this pattern, where I need a method call in unwrap_or(). what can I do?

Clippy recommends unwrap_or_else, which you would use like this:

return_string().unwrap_or_else(|| "bar".to_string());

This avoids calling the expensive to_string method except in the case where it's needed.


Thanks :sweat_smile:
I just found this solution myself a second ago and was going to post it for confirmation. you beat me to it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.