Friday, 15 August 2014

Methods and receivers in Go -



Methods and receivers in Go -

i have problems understanding methods , receivers in go. let's have code:

package main import ("fmt"; "math") type circle struct { x, y, r float64 } func (c *circle) area() float64 { homecoming math.pi * c.r * c.r } func main() { c := circle{0, 0, 5} fmt.println(c.area()) }

(c *circle) in definition of area function said receiver , in main can phone call area , pass c reference without utilize of pointers. can edit code next , works same way:

package main import ("fmt"; "math") type circle struct { x, y, r float64 } func circlearea(c *circle) float64 { homecoming math.pi * c.r*c.r } func main() { c := circle{0, 0, 5} fmt.println(circlearea(&c)) }

now syntactical difference between 2 snippets of code or there structurally different going on on deeper level?

the difference isn't syntax. method, circle type fulfill interface, function doesn't allow that:

type areaer interface { area() float64 }

go

No comments:

Post a Comment