Go language function methods

Go functions

In Go, there are both functions and methods. A method is a function that includes a receiver; the receiver can be a value or a pointer of a named type or a struct type. All methods of a given type belong to the method set of that type. The syntax format is as follows:

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

The following defines a struct type and a method of that type:

Example

package main

import (
   "fmt"  
)

/* Define struct */
type Circle struct {
  radius float64
}

func main() {
  var c1 Circle
  c1.radius = 10.00
  fmt.Println("The area of the circle = ", c1.getArea())
}

//This method belongs to the Circle type object.
func (c Circle) getArea() float64 {
  //c.radius is a property in the Circle type object
  return 3.14 * c.radius * c.radius
}

The execution result of the above code is:

圆的面积 =  314

Go functions

other extensions