Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language Function Methods

Go Language Function Methods

Go FunctionsGo Functions

Go has both functions and methods. A method is a function with a receiver, which can be a value or a pointer of a named type or a struct type. All methods of a given type belong to that type's method set. The syntax 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 a struct */

type

Circle

struct

{

  radius

float64

}

func

main

()

{

 

var

c1 Circle

  c1

.

radius

=

10

.

00

  fmt

.

Println

(

"Area of the circle = "

,

c1

.

getArea

())

}

// This method belongs to objects of the Circle type

func

(

c Circle

)

getArea

()

float64

{

 

// c.radius is the property of the Circle type object

 

return

3

.

14

c

.

radius

c

.

radius

}

The execution result of the code above is:



圆的面积 =  314

Go FunctionsGo Functions