Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why choosing `unwrap_or_else` over `unwrap_or`? [duplicate]

fn main() {
    let _one = None.unwrap_or("one".to_string());
    let _two = None.unwrap_or_else(|| "two".to_string());
}

Any particular reason why people should prefer unwrap_or_else over unwrap_or?

I have seen comments that unwrap_or is eager (this as an example). Does that mean the values in unwrap_or are always evaluated before program execution? And the FnOnce values in unwrap_or_else is called only when the program execute up to that line?

like image 763
0x00A5 Avatar asked Jun 23 '19 18:06

0x00A5


1 Answers

Both are evaluated during the program's execution and can be arbitrary values. The difference is that:

  • With unwrap_or the fallback value is evaluated just before unwrap_or is called, and therefore is evaluated whether it's needed or not (because Rust is an eager language).
  • With unwrap_or_else the fallback value is evaluated only when unwrap_or_else triggers it (by invoking the function you pass), and therefore is evaluated only if it's needed.
like image 108
Theodoros Chatzigiannakis Avatar answered Oct 15 '22 04:10

Theodoros Chatzigiannakis