I couldn't well understand why the go developers settled on a syntax like func (t Type) MethodName()
for methods. I couldn't digest this fact especially after reading this and considering the fact that go is minimalistic. Wouldn't a simpler syntax like func Type.MethodName()
or func Type::MethodName()
been sufficient with the object accessed using an implicit argument like this
or self
. Or am I missing any advantages offered by the current syntax?
The goal of that particular syntax is very particular to the language Go and cannot easily be mapped to other language syntax:
This syntax allows you to define a method set
A type may have a method set associated with it. The method set of an interface type is its interface.
- The method set of any other type
T
consists of all methods declared with receiver typeT
.- The method set of the corresponding pointer type
*T
is the set of all methods declared with receiver*T
orT
(that is, it also contains the method set ofT
).Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.
The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.
It isn't so much an "advantage" than it is a Go feature allowing to easily extend a type with new methods.
See for instance "What are some examples of Go interfaces?".
twotwotwo adds in the comments:
There are two particular things that an explicit receiver declaration lets you do:
- decide that some methods will get pointer receivers and others (e.g., non-mutating methods on small structs) don't, and
- choose a context-specific name instead of '
self
' or 'this
' (e.g., you might have afunc (srv *Server)...
).
Context-specific names are considered good style in Go
The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "
c
" or "cl
" for "Client
").Don't use generic names such as "
me
", "this
" or "self
", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions.
The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity.
Be consistent, too: if you call the receiver "c
" in one method, don't call it "cl
" in another.