Your question correctly states that any method is a function. However, the Go language must clearly distinguish between methods and functions. The reason for this is that methods have functions whose functions do not. The choice of whether Foo function or a way should be made by the programmer.
Go minimalism means that a language defines only a small set of keywords. Go authors could choose a new keyword, for example method , to distinguish methods from functions:
method Foo(receiver *T, arg1 int) {}
Looking back at the Go programming language, we see that the philosophy is to reuse existing keywords, rather than have a separate keyword for each case. A key example of this approach is the for keyword:
for {} // Infinite loop for a>0 {a--} // A while-do loop for i := range channel {} // Receive values from a channel for i:=0; i<N; i++ {} // C-style for loop
The main idea is that for the parser (and Go programmers) to distinguish between different types of for loops from each other, there is no need to enter a new keyword if the parameters can be distinguished by the syntax of what happens after the for:; := range identifier ..., their sequential order and their presence / absence.
The func keyword follows the same pattern. It can be used in several contexts:
- function definitions:
func f() {} - Function Types:
type F func(int) int - method definitions:
func (t T) SomeMethod() {} - closing:
{ ...; go func(){c<-1}(); ...} { ...; go func(){c<-1}(); ...}
From a minimalist point of view, one func keyword is simpler and more elegant than several keywords.
Optional parameter list for receiver only
func (t *T) Foo(x int) {}
allows the parser to distinguish between methods and functions:
func IDENTIFIER ... This is going to be a function func ( ... This is going to be a method
Thus, the parser (like Go programmers) can make a difference based on matching the func keyword with an identifier or ( .
user811773
source share