Go語言方法

Go編程語言支持一種叫作方法的特殊類型的函數。 在方法聲明語法中,存在“接收器”以表示函數的容器。 此接收器可用於使用“.”運算符調用函數。

語法

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

參考一個示例:

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())
}

當上述代碼編譯和執行時,它產生以下結果:

Circle area: 78.539816

上一篇: Go語言函數 下一篇: Go語言作用域規則