GO物件導向:method

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.