這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
method的文法如下:
func (r ReceiverType) methodName(parameters) (results)
go中的method是附屬在一個給定的類型上的,他的文法和函數的聲明文法幾乎一樣,只是在方法名之前增加了一個receiver,也就是method所依附的主體(可以物件導向中的對象理解)
例如下面的例子:
type Box struct {width, heigh, depth float64}func (b Box) Volume() float64 {return b.width * b.heigh * b.depth}func main(){ b:=Box{4,4,4} volume:=b.Volume()}
Volume這個method是依附於Box這個結構的。Box.Volume的發出者是Box,Volume是屬於Box的方法,而不是一個外圍函數。
更確切的說,Box擁有三個欄位width, heigh, depth,同時擁有一個方法Volume(),這些方法和欄位都屬於Box。
使用method的時候,需要注意一下幾點:
1、method的名字可以一樣,當時如果接受者不一樣,那麼method就不一樣
2、method裡可以訪問接受者的欄位
3、調用method通過.訪問,就像訪問struct裡的欄位一樣
下面是一個較為複雜的例子:
package mainimport "fmt"const (WHITE = iotaBLACKBLUEREDYELLOW)type Color bytetype Box struct {width, heigh, depth float64color Color}type BoxList []Boxfunc (b Box) Volume() float64 {return b.width * b.heigh * b.depth}func (b *Box) SetColor(c Color) {b.color = c}func (bl BoxList) BiggestBox() Box {v := 0.0var box = bl[0]for _, b := range bl {if b.Volume() > v {v = b.Volume()box = b}}return box}func (bl BoxList) PaintItBlack() {for i, _ := range bl {bl[i].SetColor(BLACK)}}func (c Color) String() string {strings := []string{"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}return strings[c]}func main() {boxes := BoxList{Box{4, 4, 4, WHITE},Box{10, 10, 1, BLUE},Box{1, 1, 20, BLACK},Box{4, 4, 4, RED},Box{20, 20, 20, WHITE},Box{100, 100, 100, RED},Box{3, 3, 3, YELLOW},}fmt.Printf("We have %d boxes in our set\n", len(boxes))fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm3")fmt.Println("The color of the last on is", boxes[len(boxes)-1].color.String())fmt.Println("The biggest on is", boxes.BiggestBox().color.String())fmt.Println("Let's paint them all black")boxes.PaintItBlack()fmt.Println("The color of the second box is", boxes[1].color.String())fmt.Println("Obviously, now, the biggest on is ", boxes.BiggestBox().color.String())}