0

I would like to write a method on a struct which borrows a value wrapped in an Option in one of its properties/fields.

Is it doable ?

Consider

struct A {}

struct Obj {
    a: Option<A>
}

impl Obj {
    fn ref_to_a(&self) -> &A {
        //&self.a.unwrap() <-- How do I implement this ?
    }
}

Playground

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101

2 Answers2

3

You can use Option::as_ref to "Convert from Option<T> to Option<&T>."

impl Obj {
    fn ref_to_a(&self) -> &A {
        self.a.as_ref().unwrap()
    }
}

Of course you shouldn't use unwrap, but at least expect.

hellow
  • 12,430
  • 7
  • 56
  • 79
  • Thanks; I actually ended up using `as_ref`. @Ömer Erden answer put me on that path. (for `unwrap`, sure, see my comment above) – Bruno Grieder May 10 '19 at 07:39
  • Is there any compiler optimization for using multiple match in here ? `as_ref` uses matching and `unwrap`(`expect`) also does, otherwise there would be unnecessary check. – Ömer Erden May 10 '19 at 09:42
  • @ÖmerErden https://godbolt.org/z/WPx_Ep – hellow May 10 '19 at 10:44
1

I don't know why you are not borrowing Option itself, but you can mimic unwrap behavior by this way :

impl Obj {
    fn ref_to_a(&self) -> &A {
        match self.a {
            Some(ref a) => return a,
            None => panic!("There is no value"),
        }
    }
}

Note : Should I avoid unwrap in production application?

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
  • 1
    Ahhh `Some(ref a)`. Thanks. (I am not borrowing the Option directly due to the way I chain functions and handle errors down the line; I do not use `unwrap`, this is a very simplified example of my use case). – Bruno Grieder May 10 '19 at 05:41