Question about calling methods on Rc<T>

When calling methods on type T in a Rc how does rust know to de-reference the Rc for me?

For example:

let x = Rc::new(String::new());
let y = x.len();

In this case rust knows that I am trying to get the length of the String inside the Rc. How does this work? Is this the implicit deref coercion at work?

This is due to the Deref trait. In short, if T1: Deref<Target = T2>, then any &T1 can be treated as &T2.

thank you for your clarification :slight_smile:

And in x.len() there is an implicit &x taking place thanks to the . operator auto-ref: since x: Rc<String> has no inherent .len() method, nor one from a trait, then Rust will try to call .len() on &x: &Rc<String>, and that's when a Deref coercion happens so that .len() ends up called on &*x: &String.

1 Like

Wow, that is something I had not totally grasped before.

The "." in x.len() is going to keep deferencing, if it can, until it finds a len() function.

Which means I can write:

fn main () {
    use ::std::rc::Rc;
    
    let x: Rc<Rc<Rc<Rc<Rc<String>>>>> = Rc::new(Rc::new(Rc::new(Rc::new(Rc::new("Hello, World!".into())))));
    let y = x.len();
    println!("x.len() = {:?}", y);
}

Awesome!

Is there an obfuscated Rust competition yet by the way?

1 Like