Beginner: Why does the variable of Rc<MyStruct> type can be used as MyStruct type when call methods or accessing members

Here is a demo:

struct MyStruct {
    int_val: i32,
    str_val: String,
}
let var = Rc::new(MyStruct { int_val: 0, str_val: String::from("hello")});
println!("string of var = {}", var.str_val);

It should use deference operator (*) to var, like this: (*var).str_val.

I know a bit about deref coercion. When a variable of &Vec[String] type passed to a function which accept a parameter of &[str] is allowed because of deref coercion.

So, is this a deref coercion ?

Hi, what you are experiencing is the dot operator “magic”, you can learn more about it here or there.

1 Like

Thanks a lot. I guess I figure out it !

Since Rc<MyStruct> implements Deref<Target = MyStruct>, (*val).str_val is indeed the required path to access the str_val field behind the Rc pointer; provided the . operator works like in C/C++ (field/method access, no dereference).

However, as @leudz documentation shows, the . operator in Rust is more powerful than it seems:

  • it can auto-dereference (* operator) if needed; for instance, it can behave as the -> operator in C/C++ (your case here),

  • and also auto-reference (& or &mut operators): this is why you don’t need to explicit & or &mut when calling methods.

4 Likes

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