Deref coercions of rust book

Even though f isn’t a reference, and foo takes &self, this works. That’s because these things are the same:

f.foo();
(&f).foo();
(&&f).foo();
(&&&&&&&&f).foo();

A value of type &&&&&&&&&&&&&&&&Foo can still have methods defined on Foo called, because the compiler will insert as many * operations as necessary to get it right. And since it’s inserting *s, that uses Deref.


f.foo() 

vs

(&f).foo();

vs

(&&f).foo();
(&&&&&&&&f).foo();

I understand the later two part is equivalent because of auto Deref.

but the first one is not a ref? how does it works?

Is there a special places to ask question related to the rust book? I feel it might not be appropriate to ask question directly related to the book, but did not find another places.

Method calls will automatically borrow the subject if necessary; the first is syntactic sugar for the second, because if it wasn't, writing Rust would be rather unpleasant.

1 Like