Latest web development tutorials

Go language function method

Go function Go function

Go language has functions and methods at the same time. A method is a function that contains the recipient, the recipient can be a value named type or structure type or a pointer. All methods of a given type belonging to the type of collection method. Syntax is as follows:

func (variable_name variable_data_type) function_name() [return_type]{
   /* 函数体*/
}

The following definition of a structure type and a method of this type:

package main

import (
   "fmt"  
)

/* 定义函数 */
type Circle struct {
  radius float64
}

func main() {
  var c1 Circle
  c1.radius = 10.00
  fmt.Println("Area of Circle(c1) = ", c1.getArea())
}

//该 method 属于 Circle 类型对象中的方法
func (c Circle) getArea() float64 {
  //c.radius 即为 Circle 类型对象中的属性
  return 3.14 * c.radius * c.radius
}

The above code is executed as a result of:

Area of Circle(c1) =  314

Go function Go function