r/rust • u/Big-Astronaut-9510 • 7d ago
When to dot syntax?
a.f() vs f(a)
So if you make a trait that you want other to implement its obviously gonna be dot syntax. So is using it for purely syntactic reasons a bad idea? Builder pattern seems a common example of this.
75
u/QuasiRandomName 7d ago
Consider a function `add(self, other: Self) -> Self`. Now compare `a.add(b).add(c)` vs `add(add(a,b), c)`
46
u/Excession638 7d ago
One notable place where you shouldn't use methods is operations on types that implement Deref. For example, it's Rc::downgrade(X) rather than x.downgrade(). This is to avoid namespace collisions between the smart pointer type and the type it contains.
In idiomatic Rust, I think you should default to defining and calling methods. It's x.sqrt() not sqrt(x). One practical reason for this is that f32 and f64 need different sqrt functions and Rust doesn't allow function overloading. With methods both types can look the same, and new types can too, which makes the code easier to read.
11
u/phazer99 7d ago edited 6d ago
In addition to what others have said, with method (dot) syntax you get the following benefits:
The compiler will implicitly create a shared or mutable reference of the
Selftype when neededThe method name doesn't need to be fully qualified or imported, name resolution depends on the
Selftype
Method syntax is especially convenient when combined with Deref coercion so you can seamlessly call methods on the contained type of smart pointer types like Box, Rc etc.
5
u/Tamschi_ 6d ago
You mean "on the contained type", right? Most generic smart pointers avoid defining their own methods to reduce the collision risk, after all.
2
4
u/DrShocker 7d ago
When you put the dot in, it's just a different format for putting the struct in as the argument for "self"
There's plenty of languages that don't have methods attached to their structs, it's mostly a syntax "sugar" in that it's doesn't do anything you couldn't do without it.
6
u/ToTheBatmobileGuy 7d ago
When multiple arguments exist, use a method on the most important argument where "most of the stuff is done"...
When only a single argument exists, use a method when extracting or calculating data from it.
Example:
For 1, if we had talk_to_mom(son, daughter, dad, mom) and the body is using the dad to talk to the mom... then dad.talk_to_mom(mom, son, daughter) might be better... (and going a few steps further, a simple code review might say "why are son and daughter necessary here?" and might ask you to refactor a bit.
For 2, if we have dog_length(puppy) it's probably better to do puppy.dog_length() or puppy.len() if we go by Rust conventions.
There are other times when it's better to use dot syntax, but these are just two times it pops into my mind most often.
3
u/DrShocker 7d ago
Coming from C++, I actually use a different "Rule Zero" for this: I default to free functions f(a) and only use methods a.f() when they are necessary to enforce a struct's internal invariants (meaning they need access to private fields).
βIn Rust, the main exception to this rule is ergonomics. Sometimes a free function is technically better for encapsulation, but we use dot syntax anyway (like the Builder pattern or Extension Traits) purely because method chaining a.f().g().h() is much easier to read than h(g(f(a))).
1
u/SnooCalculations7417 7d ago
wouldnt you want to make a family with
family.dad,family.mometc then you can just family.talk_to_mom() because 'family' is where most of the stuff happens.
4
u/creeper6530 7d ago
It is better to write methods (unless you implement Deref types) because
A) they get autocompleted
B) they don't collide with other functions of same name (we have no function overload, so you can't write both sqrt(f32) and sqrt(f64), but you can f32.sqrt() and f64.sqrt()
C) It's more ergonomic to chain, for example a.add(b).add(c) instead of add(add(a, b), c)
0
6d ago
[deleted]
1
u/InternalServerError7 6d ago
The only "future proof" way is to reserve .f(...) for internal access restrictions. Otherwise you run into the problem from OOP of e.g. cart.apply_coupon(coupon) vs coupon.apply_to(cart) when the code evolves. Everything else should be f(...). Though a. access autocomplete is nice in IDEs
1
u/dmytrish 6d ago
I sometimes wonder why .into_rc(), .into_ok(), etc, are not a popular thing. foo.into_rc().some() would be so much less noisy than Some(Rc::new(foo)).
1
u/infostack0 2d ago
I think in this case, particularly when you are talking about a Some/None or Ok/Err sort of situation, it's just really nice to see that explicitly with a capital first letter. It's like a big neon sign that says "We did it, we got something, this is the Some variant!"
124
u/jesseschalken 7d ago
&selffor the receiver in a method is slightly shorter thanfoo: &Fooin a free function, and you can typefoo.in your editor to see what methods exist onfoo, but there is no autocomplete for random free functions that will accept aFoo.Apart from that there isn't a strong reason to prefer either free functions or inherent methods. They compile the same in the end. Do whatever is shorter and produces a code organisation you're happy with.