Rust Option Unwrapping a reference to an Option owning its contents


Example

A reference to an option &Option<T> cannot be unwrapped if the type T is not copyable. The solution is to change the option to &Option<&T> using as_ref().

Rust forbids transferring of ownership of objects while the objects are borrowed. When the Option itself is borrowed (&Option<T>), its contents is also — indirectly — borrowed.

#[derive(Debug)]
struct Foo;
 
fn main() {
    let wrapped = Some(Foo);
    let wrapped_ref = &wrapped;
    
    println!("{:?}", wrapped_ref.unwrap()); // Error!
}

cannot move out of borrowed content [--explain E0507]

However, it is possible to create a reference to the contents of Option<T>. Option's as_ref() method returns an option for &T, which can be unwrapped without transfer of ownership:

println!("{:?}", wrapped_ref.as_ref().unwrap());