[resolved] Using ?-operator with references

  1. I have this code snippet:

pub struct Foo {
    pub t: i32,
}

pub struct Bar {
    pub x: Option<Foo>,
}


impl Bar {
    pub fn test(&self) -> Option<i32> {
        let y = &self.x?;
        Some(y.t + 2)
    }
}
  1. The point here is not to call some function that does ( (A -> B), Option<A>) -> Option<B>

  2. The point here is that I have an "&Option", and I want to use the ? operator to extract a &A (and short circuit exit if it's None).

  3. Why can't I do this?

Oh, and the error I get:

   |
25 |         let s = &self.opt_deriv?;
   |                  ^^^^^^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

Rust playground link: Rust Playground

The order of operations is different from you think. To get an inner &A, use self.opt_deriv.as_ref()?.

1 Like

That fixed. it. Thanks!