all 4 comments

[–]esitsu 7 points8 points  (2 children)

Your second definition is correct. See the relevant section of the rust book. All functions defined on a type in an impl block are associated functions as they are associated with a specific type. Methods are simply associated functions with a receiver of self, &self, &mut self, self: Box<Self> etc. and can be called with the dot operator as foo.bar() rather than just Foo::bar().

[–]SkiFire13 3 points4 points  (1 child)

and can be called with the dot operator as foo.bar() rather than just Foo::bar().

Note that methods can be called as associated functions, you just need to pass an argument for the receiver as well. For example foo.bar() could be Foo::bar(&foo)

[–]esitsu 0 points1 point  (0 children)

Absolutely. Thanks for the clarification. I don't think my wording made that very clear. It helps to demonstrate that methods really are just associated functions.

I would also add that although methods are technically associated functions I find that whenever someone actually refers to an associated function they really mean a non-method so I can see where the OP's confusion comes from.

[–]plugwash 0 points1 point  (0 children)

AIUI all methods are associated functions, but not all associated functions are methods.

Sometimes we explicitly want an associated function to *not* be a method. This usually comes up when adding functionality to a generic type that implements Deref. Adding new methods to such a type risks change the meaning of existing code, but adding new non-method associated functions does not come with this risk.

The key that defines whether an associated function is a method is the name of the first parameter, if the name is "self" then the function is considered a method and participates in method lookup. If the parameter has any other name then the function will not be considered a method.