News for hackers. Stuff that matters.
Re:Rust from 0 to 80% for JavaScript Developers by zozbot234 on Sunday May 01, 2022 @06:01AM (#31223618)
There can be additional differences in call syntax due to Deref support, which can delegate methods from a "child" to a "parent" type. For example, if we have puss: Rc<Cat> then puss.clone(); will implicitly call Cat::clone and return a new owned Cat (which can add overhead and is not zero cost) , whilst Rc::clone(puss) will simply create a new Rc reference to the same Cat object.
Re:Rust from 0 to 80% for JavaScript Developers by tialaramex on Sunday May 01, 2022 @06:31AM (#31223788)
> For example, if we have puss: Rc<Cat> then puss.clone(); will implicitly call Cat::clone

[Edited, this used to suggest it's a typo, but probably it's just a different way to think about what's happening, so I removed this claim]. There almost certainly isn't a Cat::clone and in fact what's happening is that Clone is in the prelude, so this is:

Clone::clone(&puss)

[edited to add]

Which is really even:

<Cat as Clone>::clone(&puss)

and because Rc is a Smart Pointer it implements DeRef and so that's ultimately:

<Cat as Clone>::clone(<Rc as Deref>::deref(&puss))

Definitely understandable that people want to write puss.clone() instead.

By the way, misfortunate::Multiplicity demonstrates Deref and DerefMut nicely, providing a type which has two things inside it but references to it act like one thing when being mutated and like the other when merely referenced...

Not something for absolute beginners, but worth seeing to build correct intuitions (and to underscore Rust's admonition not to implement Deref and DerefMut if you aren't a smart pointer -- misfortunate is like Jackass, this is for entertainment and not to be attempted in your real Rust projects).