Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale for Go's method syntax

Tags:

go

Ok, I have to admit, I don't really use Go very much at all, but I did just observe something that strikes me as odd for a language that strives for minimality and all that good stuff as Go does. I would be surprised if there isn't a legitimate rationale behind it, so that's what I'm looking for.

So when you have a method, you define it like this:

func (s *SomeStruct) Foo(x int) { }

but why have an extra parameter list just for the "receiver", as I think it's called? Would it not be a simpler and more elegant design to just do

func Foo(s *SomeStruct, x int) { }

and then have s.Foo(5) just be translated to a call to a function Foo(s, 5)?

like image 454
chisophugis Avatar asked Mar 18 '12 14:03

chisophugis


People also ask

What is the purpose of Go's compiler?

Go is a compiled language. This means we must run our source code files through a compiler, which reads source code and generates a binary, or executable, file that is used to run the program.

What Is syntax like in Go?

Syntax. Go's syntax includes changes from C aimed at keeping code concise and readable. A combined declaration/initialization operator was introduced that allows the programmer to write i := 3 or s := "Hello, world!" , without specifying the types of variables used.

Why was go language created?

Go was intended as a language for writing server programs that would be easy to maintain over time. (See this article for more background.) The design concentrated on things like scalability, readability, and concurrency.


1 Answers

Methods are fundamentally special and different from regular functions.

  • Methods must live in the same package as the receiver type.
  • Methods are used to satisfy interfaces.
  • Receiver parameters are the only parameters which may be overloaded.
  • When anonymous struct fields have methods, those methods are "inherited".

With your proposal, the line between a function and a method becomes very blurry and it's difficult to figure out how to resolve the above issues.

That said, I think it would be really interesting to design a language with multimethods and interfaces. However, that language would not be Go.

like image 158
Evan Shaw Avatar answered Oct 16 '22 04:10

Evan Shaw