Why can't I match against a Rc<Option<T>>?

Hello Rustineers!

Please consider the following snippet.

use std::rc::Rc;

fn main() {
    let rcnone: Rc<Option<String>> = Rc::new(None);
    match rcnone {
        Some(_) => panic!(),
        None => println!("yep.")
    }
}

Why doesn't it work? I have to explicitly match *rcnone and not rcnone to make it compile, but I thought the point of the dereference trait which Rc implements was to avoid having to dereferencing things?

Thanks in advance for the explanation, have a beautiful day!

Autoderef does not happen everywhere. If it was the case, it would be impossible to access wrapper objects that implement Deref.

There are certain situations in which autoderef occurs (called "coercion sites"), for example when calling a method. Your example is not such a place, so you have to perform the deref manually.

No, it's not. Deref is a formalism for expressing that a type is an owning pointer-like wrapper, and a hook into the language for overriding the prefix * operator. Auto-deref is mainly a convenience feature.

3 Likes