? operator for &Option<_>

I repeatedly got this error:

the ? operator cannot be applied to type &std::option::Option<...>
= help: the trait std::ops::Try is not implemented for &std::option::Option<...>
= note: required by std::ops::Try::into_result

And always ended up using a if let Some(...) = ... { ... } else { return None; }.

Why is there no ? operator for &Option?

Works for me

fn foo(r: Option<u32>) -> Option<u32> {
    Some(r?+1)
}

fn main() {
    println!("{:?}", foo(Some(3)));
}

Maybe you need to update your compiler? (rustup update).

You are trying to apply ? on a reference of Option. You need to dereference it (*foo). There's no need for a &Option. If that's an function argument, please accept Option<&T> where T is of course your concrete type, instead of &Option<T>.

You can use as_ref()? to go from &Option<T> to Option<&T> and unwrap it.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.