rusttype-systems

Why can std::rc::Rc call its own value's methods?


I'm a newbie to Rust and type-systems. I'm reading rustc/rc.rs. I don't know why Rc<T> can call T's methods. What conditions does a Structure<T> satisfy for calling methods of the wrapped value?

use std::rc::Rc;

fn main() {
    let a = Rc::new("The quick fox".to_string());
    println!("{}", a.contains("white")); // Rc<String> can call String#contains.
}

Solution

  • This property is called "Deref coercion".

    If you have two types T and U, such that T: Deref<Target = U>, then everywhere you have a &T, you can coerce it to &U. In particular, as method call syntax is just sugar to the functions taking &self (or &mut self, or self - depending on the method), you can call methods on the U having only T.

    As you can see in the docs, Deref is implemented for Rc, as it is for almost any other smart pointer (the "active" smart pointers like Mutex, which involve explicit locking, being notable exception). So, when you have one of these smart pointers, you can treat a reference to it as the reference to the inner value - see also this question about other consequences of this fact.

    More info on this topic could be also found in the Rust book.