Omid
Omid

Reputation: 2677

Methods and receivers in Go

I have problems understanding methods and receivers in Go. Let's say we have this code:

package main
import ("fmt"; "math")
type Circle struct {
    x, y, r float64
}
func (c *Circle) area() float64 {
    return math.Pi * c.r * c.r
}
func main() {
    c := Circle{0, 0, 5}
    fmt.Println(c.area())
}

(c *Circle) in the definition of the area function is said to be a receiver and in the main we can call area and pass c by reference without the use of pointers. I can edit the code to the following and it works the same way:

package main
import ("fmt"; "math")
type Circle struct {
    x, y, r float64
}
func circleArea(c *Circle) float64 {
    return math.Pi * c.r*c.r
}
func main() {
    c := Circle{0, 0, 5}
    fmt.Println(circleArea(&c))
}

Now is this just a syntactical difference between the two snippets of code or is there something structurally different going on on a deeper level?

Upvotes: 2

Views: 90

Answers (1)

andybalholm
andybalholm

Reputation: 16170

The difference isn't just syntax. With a method, your circle type could fulfill an interface, but the function doesn't let you do that:

type areaer interface {
    area() float64
}

Upvotes: 6

Related Questions