1

I want to create a helper function that returns the value of an Option if available else it returns the default case.

fn get_val(&self) -> &Val {
    return if self.my_val.is_none() {
        &self.default
    } else {
        &self.my_val.unwrap()
    };
}

I can't do this because the unwrap function's result is short lived.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ZNackasha
  • 755
  • 2
  • 9
  • 29
  • 3
    The whole docs on `Option` is quite a read, but you might be particularly interested in [unwrap_or method](https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or). – Michail Oct 23 '18 at 17:34
  • This is defiantly interesting but I still have the same issue. which is the result of the function is still fixed to the scope of the function. hence I cannot return the borrow. – ZNackasha Oct 23 '18 at 17:43
  • 2
    please include an [mcve]. – Stargateur Oct 23 '18 at 17:50
  • 1
    Applying the duplicate to your specific case: `fn get_val(&self) -> &Val { self.my_val.as_ref().unwrap_or(&self.default) }`. – Shepmaster Oct 23 '18 at 17:58
  • Thanks everybody that helped! – ZNackasha Oct 23 '18 at 18:02

0 Answers0