Functions and Methods in Go

In the previous post on Go I’ve used the words method and function interchangeably, but as I learn more about Go I find that – in Go, methods and functions are actually different.

First off, let me point you to this post Part 17: Methods which covers this subject in more depth. But here’s the elevator pitch.

Methods names can be overloaded and the syntax of using a method is more like a method on an object.

Let’s look at a simple example, a classic sort of OO example. We have different shape types and each has an area method.

This is example is taken from Part 17: Methods

type Rectangle struct {
   length float64
   width float64
}

type Circle struct {
   radius float64
}

func (shape Rectangle) Area() float64 {
   return shape.length * shape.width
}

func (shape Circle) Area() float64 {
   return math.Pi * math.Pow(shape.radius, 2)
}

Notice that a method has the type declared before the method name (unlike a function) and this is because we call it in the way we would an extension method and object’s method in C#.

In Go the type declared after the function name (function syntax) is known as an argument, whereas a type declared before the function name (method syntax) is known as a receiver.

For example

r := Rectangle{ length = 100, width = 23 }
c := Circle { radius = 30 }

rArea := r.Area()
cArea := c.Area()