2

In Scala, I can use getOrElse as a convenient way to get a default value from Option, what's the equivalent of this in Rust?

val threeOpt = Some(3)
val shouldBeThree = threeOpt.getOrElse(-1) // got 3
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Renkai
  • 1,991
  • 2
  • 13
  • 18
  • 6
    Please note that the standard structs are documented: https://doc.rust-lang.org/std/option/enum.Option.html – Denys Séguret Nov 04 '19 at 13:16
  • 5
    Note to close voters: while the question shows no research effort, that is not grounds for closing. Downvote, instead, and move on, or merely ignore it. [Relevant Meta link.](https://meta.stackoverflow.com/questions/260828/do-we-need-a-close-reason-for-zero-effort-questions) – trent Nov 04 '19 at 13:39
  • 4
    Good question! I think. @trentcl "while the question shows no research effort" — the linked rust-lang docs is a 500 - 1000 lines page, and then I think it makes sense to ask. Isn't one of the points with SO to avoid having to spend so much time reading "everything", and instead find answers quickly. Also, coming from a Scala background, "unwrap ..." is an unexpected name, and, personally, I was wondering if there's some "get ..." function I hadn't found. (I'm not OP, just another Scala & now Rust user.) – KajMagnus Nov 07 '21 at 09:09
  • 2
    (B.t.w @trentcl agreed anyway that it's no grounds for closing, good point) – KajMagnus Nov 07 '21 at 13:40

1 Answers1

10

You can use either unwrap_or or unwrap_or_else

  • unwrap_or is eagerly evaluated
  • unwrap_or_else is lazily evaluated

See here for differences between eager and lazy

ecoe
  • 4,994
  • 7
  • 54
  • 72
Shankar Shastri
  • 1,134
  • 11
  • 18