Go - Method


Advertisements

Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call a function using "." operator. For example −

Syntax

func (variable_name variable_data_type) function_name() [return_type]{
   /* function body*/
}

Example

package main

import (
   "fmt" 
   "math" 
)

/* define a circle */
type Circle struct {
   x,y,radius float64
}

/* define a method for circle */
func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

func main(){
   circle := Circle{x:0, y:0, radius:5}
   fmt.Printf("Circle area: %f", circle.area())
}

When the above code is compiled and executed, it produces the following result −

Circle area: 78.539816
go_functions.htm
Advertisements