Go Struct Methods

Introduction

Suppose we have

type Circle struct { 
    x float64 
    y float64 
    r float64 
} 

We can add method to Circle

func (c *Circle) area() float64 { 
    return math.Pi * c.r*c.r 
} 

In between the keyword func and the name of the function, we've added a receiver.

The receiver is like a parameter.

The receiver has a name and a type.

It allows us to call the function using the . operator:

fmt.Println(c.area()) 

Example

package main/* w w  w.  j  av  a2s .  co m*/

import "fmt"

type Rectangle struct { 
    x1, y1, x2, y2 float64 
} 

func (r *Rectangle) area() float64 { 
    return 20
} 

func main(){

     r  := Rectangle{0, 0, 10, 10} 
     fmt.Println(r.area()) 

}



PreviousNext

Related