I'm curious what is idiomatic way of calling functions that comes from trait implementations. Technically they can be called as functions that have explicit reference to struct passed in or as a methods of struct. I can see that former version has some preference over latter in Rust Book, but I personally find it strange, since for the same object Rust Book uses method syntax for other operations implemented for the struct (methods that are not come from trait implementations).
use std::rc::Rc;
fn main() {
let rc = Rc::new(5);
// Which call to clone is seen as idomatic?
let c1 = Rc::clone(&rc);
let c2 = rc.clone();
println!("{} {} {}", *rc, *c1, *c2);
}
Most trait methods should be called with dot syntax.
However, for Rc::clone() and Arc::clone() and both's Weak::clone() specifically, some people (including me) prefer to use them with UFCS (Rc::clone(&v) and not v.clone()), in order to not confuse them with most Clone implementation that usually perform a deep copy. As mentioned by @prog-fh, there is also a Clippy lint for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With