<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                前面兩章我們介紹了函數和struct,那你是否想過函數當作struct的字段一樣來處理呢?今天我們就講解一下函數的另一種形態,帶有接收者的函數,我們稱為`method` ## [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.5.md#method)method 現在假設有這么一個場景,你定義了一個struct叫做長方形,你現在想要計算他的面積,那么按照我們一般的思路應該會用下面的方式來實現 ~~~ package main import "fmt" type Rectangle struct { width, height float64 } func area(r Rectangle) float64 { return r.width*r.height } func main() { r1 := Rectangle{12, 2} r2 := Rectangle{9, 4} fmt.Println("Area of r1 is: ", area(r1)) fmt.Println("Area of r2 is: ", area(r2)) } ~~~ 這段代碼可以計算出來長方形的面積,但是area()不是作為Rectangle的方法實現的(類似面向對象里面的方法),而是將Rectangle的對象(如r1,r2)作為參數傳入函數計算面積的。 這樣實現當然沒有問題咯,但是當需要增加圓形、正方形、五邊形甚至其它多邊形的時候,你想計算他們的面積的時候怎么辦啊?那就只能增加新的函數咯,但是函數名你就必須要跟著換了,變成`area_rectangle, area_circle, area_triangle...` 像下圖所表示的那樣, 橢圓代表函數, 而這些函數并不從屬于struct(或者以面向對象的術語來說,并不屬于class),他們是單獨存在于struct外圍,而非在概念上屬于某個struct的。 [![](https://github.com/astaxie/build-web-application-with-golang/raw/master/zh/images/2.5.rect_func_without_receiver.png?raw=true)](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/images/2.5.rect_func_without_receiver.png?raw=true) 圖2.8 方法和struct的關系圖 很顯然,這樣的實現并不優雅,并且從概念上來說"面積"是"形狀"的一個屬性,它是屬于這個特定的形狀的,就像長方形的長和寬一樣。 基于上面的原因所以就有了`method`的概念,`method`是附屬在一個給定的類型上的,他的語法和函數的聲明語法幾乎一樣,只是在`func`后面增加了一個receiver(也就是method所依從的主體)。 用上面提到的形狀的例子來說,method?`area()`?是依賴于某個形狀(比如說Rectangle)來發生作用的。Rectangle.area()的發出者是Rectangle, area()是屬于Rectangle的方法,而非一個外圍函數。 更具體地說,Rectangle存在字段length 和 width, 同時存在方法area(), 這些字段和方法都屬于Rectangle。 用Rob Pike的話來說就是: > "A method is a function with an implicit first argument, called a receiver." method的語法如下: ~~~ func (r ReceiverType) funcName(parameters) (results) ~~~ 下面我們用最開始的例子用method來實現: ~~~ package main import ( "fmt" "math" ) type Rectangle struct { width, height float64 } type Circle struct { radius float64 } func (r Rectangle) area() float64 { return r.width*r.height } func (c Circle) area() float64 { return c.radius * c.radius * math.Pi } func main() { r1 := Rectangle{12, 2} r2 := Rectangle{9, 4} c1 := Circle{10} c2 := Circle{25} fmt.Println("Area of r1 is: ", r1.area()) fmt.Println("Area of r2 is: ", r2.area()) fmt.Println("Area of c1 is: ", c1.area()) fmt.Println("Area of c2 is: ", c2.area()) } ~~~ 在使用method的時候重要注意幾點 * 雖然method的名字一模一樣,但是如果接收者不一樣,那么method就不一樣 * method里面可以訪問接收者的字段 * 調用method通過`.`訪問,就像struct里面訪問字段一樣 圖示如下: [![](https://github.com/astaxie/build-web-application-with-golang/raw/master/zh/images/2.5.shapes_func_with_receiver_cp.png?raw=true)](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/images/2.5.shapes_func_with_receiver_cp.png?raw=true) 圖2.9 不同struct的method不同 在上例,method area() 分別屬于Rectangle和Circle, 于是他們的 Receiver 就變成了Rectangle 和 Circle, 或者說,這個area()方法 是由 Rectangle/Circle 發出的。 > 值得說明的一點是,圖示中method用虛線標出,意思是此處方法的Receiver是以值傳遞,而非引用傳遞,是的,Receiver還可以是指針, 兩者的差別在于, 指針作為Receiver會對實例對象的內容發生操作,而普通類型作為Receiver僅僅是以副本作為操作對象,并不對原實例對象發生操作。后文對此會有詳細論述。 那是不是method只能作用在struct上面呢?當然不是咯,他可以定義在任何你自定義的類型、內置類型、struct等各種類型上面。這里你是不是有點迷糊了,什么叫自定義類型,自定義類型不就是struct嘛,不是這樣的哦,struct只是自定義類型里面一種比較特殊的類型而已,還有其他自定義類型申明,可以通過如下這樣的申明來實現。 ~~~ type typeName typeLiteral ~~~ 請看下面這個申明自定義類型的代碼 ~~~ type ages int type money float32 type months map[string]int m := months { "January":31, "February":28, ... "December":31, } ~~~ 看到了嗎?簡單的很吧,這樣你就可以在自己的代碼里面定義有意義的類型了,實際上只是一個定義了一個別名,有點類似于c中的typedef,例如上面ages替代了int 好了,讓我們回到`method` 你可以在任何的自定義類型中定義任意多的`method`,接下來讓我們看一個復雜一點的例子 ~~~ package main import "fmt" const( WHITE = iota BLACK BLUE RED YELLOW ) type Color byte type Box struct { width, height, depth float64 color Color } type BoxList []Box //a slice of boxes func (b Box) Volume() float64 { return b.width * b.height * b.depth } func (b *Box) SetColor(c Color) { b.color = c } func (bl BoxList) BiggestColor() Color { v := 0.00 k := Color(WHITE) for _, b := range bl { if bv := b.Volume(); bv > v { v = bv k = b.color } } return k } 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, RED}, Box{10, 10, 1, YELLOW}, Box{1, 1, 20, BLACK}, Box{10, 10, 1, BLUE}, Box{10, 30, 1, WHITE}, Box{20, 20, 20, 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 one is",boxes[len(boxes)-1].color.String()) fmt.Println("The biggest one is", boxes.BiggestColor().String()) fmt.Println("Let's paint them all black") boxes.PaintItBlack() fmt.Println("The color of the second one is", boxes[1].color.String()) fmt.Println("Obviously, now, the biggest one is", boxes.BiggestColor().String()) } ~~~ 上面的代碼通過const定義了一些常量,然后定義了一些自定義類型 * Color作為byte的別名 * 定義了一個struct:Box,含有三個長寬高字段和一個顏色屬性 * 定義了一個slice:BoxList,含有Box 然后以上面的自定義類型為接收者定義了一些method * Volume()定義了接收者為Box,返回Box的容量 * SetColor(c Color),把Box的顏色改為c * BiggestColor()定在在BoxList上面,返回list里面容量最大的顏色 * PaintItBlack()把BoxList里面所有Box的顏色全部變成黑色 * String()定義在Color上面,返回Color的具體顏色(字符串格式) 上面的代碼通過文字描述出來之后是不是很簡單?我們一般解決問題都是通過問題的描述,去寫相應的代碼實現。 ### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.5.md#指針作為receiver)指針作為receiver 現在讓我們回過頭來看看SetColor這個method,它的receiver是一個指向Box的指針,是的,你可以使用*Box。想想為啥要使用指針而不是Box本身呢? 我們定義SetColor的真正目的是想改變這個Box的顏色,如果不傳Box的指針,那么SetColor接受的其實是Box的一個copy,也就是說method內對于顏色值的修改,其實只作用于Box的copy,而不是真正的Box。所以我們需要傳入指針。 這里可以把receiver當作method的第一個參數來看,然后結合前面函數講解的傳值和傳引用就不難理解 這里你也許會問了那SetColor函數里面應該這樣定義`*b.Color=c`,而不是`b.Color=c`,因為我們需要讀取到指針相應的值。 你是對的,其實Go里面這兩種方式都是正確的,當你用指針去訪問相應的字段時(雖然指針沒有任何的字段),Go知道你要通過指針去獲取這個值,看到了吧,Go的設計是不是越來越吸引你了。 也許細心的讀者會問這樣的問題,PaintItBlack里面調用SetColor的時候是不是應該寫成`(&bl[i]).SetColor(BLACK)`,因為SetColor的receiver是*Box,而不是Box。 你又說對的,這兩種方式都可以,因為Go知道receiver是指針,他自動幫你轉了。 也就是說: > 如果一個method的receiver是*T,你可以在一個T類型的實例變量V上面調用這個method,而不需要&V去調用這個method 類似的 > 如果一個method的receiver是T,你可以在一個*T類型的變量P上面調用這個method,而不需要 *P去調用這個method 所以,你不用擔心你是調用的指針的method還是不是指針的method,Go知道你要做的一切,這對于有多年C/C++編程經驗的同學來說,真是解決了一個很大的痛苦。 ### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.5.md#method繼承)method繼承 前面一章我們學習了字段的繼承,那么你也會發現Go的一個神奇之處,method也是可以繼承的。如果匿名字段實現了一個method,那么包含這個匿名字段的struct也能調用該method。讓我們來看下面這個例子 ~~~ package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human //匿名字段 school string } type Employee struct { Human //匿名字段 company string } //在human上面定義了一個method func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() } ~~~ ### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.5.md#method重寫)method重寫 上面的例子中,如果Employee想要實現自己的SayHi,怎么辦?簡單,和匿名字段沖突一樣的道理,我們可以在Employee上面定義一個method,重寫了匿名字段的方法。請看下面的例子 ~~~ package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human //匿名字段 school string } type Employee struct { Human //匿名字段 company string } //Human定義method func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } //Employee的method重寫Human的method func (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //Yes you can split into 2 lines here. } func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() } ~~~ 上面的代碼設計的是如此的美妙,讓人不自覺的為Go的設計驚嘆! 通過這些內容,我們可以設計出基本的面向對象的程序了,但是Go里面的面向對象是如此的簡單,沒有任何的私有、公有關鍵字,通過大小寫來實現(大寫開頭的為公有,小寫開頭的為私有),方法也同樣適用這個原則。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看