golang interface介面

來源:互聯網
上載者:User

標籤:set   面積   diff   length   編譯   range   接收   int   sid   

package mainimport "fmt"type Shaper interface {Area() float32}type Square struct {side float32}func (sq *Square) Area() float32 {return sq.side * sq.side}func main() {sq1 := new(Square)sq1.side = 5var areaIntf ShaperareaIntf = sq1// shorter,without separate declaration:// areaIntf := Shaper(sq1)// or even:// areaIntf := sq1fmt.Printf("The square has area: %f\n", areaIntf.Area())}

  

上面的程式定義了一個結構體 Square 和一個介面 Shaper,介面有一個方法 Area()

在 main() 方法中建立了一個 Square 的執行個體。在主程式外邊定義了一個接收者類型是 Square 方法的 Area(),用來計算正方形的面積:結構體 Square 實現了介面 Shaper 。

所以可以將一個 Square 類型的變數賦值給一個介面類型的變數:areaIntf = sq1 。

現在介面變數包含一個指向 Square 變數的引用,通過它可以調用 Square 上的方法 Area()。當然也可以直接在 Square 的執行個體上調用此方法,但是在介面執行個體上調用此方法更令人興奮,它使此方法更具有一般性。介面變數裡包含了接收者執行個體的值和指向對應方法表的指標。

這是 多態 的 Go 版本,多態是物件導向編程中一個廣為人知的概念:根據當前的類型選擇正確的方法,或者說:同一種類型在不同的執行個體上似乎表現出不同的行為。

如果 Square 沒有實現 Area() 方法,編譯器將會給出清晰的錯誤資訊:

cannot use sq1 (type *Square) as type Shaper in assignment:*Square does not implement Shaper (missing Area method)

  如果 Shaper 有另外一個方法 Perimeter(),但是Square 沒有實現它,即使沒有人在 Square 執行個體上調用這個方法,編譯器也會給出上面同樣的錯誤。

擴充一下上面的例子,類型 Rectangle 也實現了 Shaper 介面。接著建立一個 Shaper 類型的數組,迭代它的每一個元素並在上面調用 Area() 方法,以此來展示多態行為:

package mainimport "fmt"type Shaper interface {Area() float32}type Square struct {side float32}func (sq *Square) Area() float32 {return sq.side * sq.side}type Rectangle struct {length, width float32}func (r Rectangle) Area() float32 {return r.length * r.width}func main() {r := Rectangle{5, 3} // Area() of Rectangle needs a valueq := &Square{5}      // Area() of Square needs a pointer// shapes := []Shaper{Shaper(r), Shaper(q)}// or shortershapes := []Shaper{r, q}fmt.Println("Looping through shapes for area ...")for n, _ := range shapes {fmt.Println("Shape details: ", shapes[n])fmt.Println("Area of this shape is: ", shapes[n].Area())}}

  在調用 shapes[n].Area() 這個時,只知道 shapes[n] 是一個 Shaper 對象,最後它搖身一變成為了一個 Square 或 Rectangle 對象,並且表現出了相對應的行為。

在調用 shapes[n].Area() 這個時,只知道 shapes[n] 是一個 Shaper 對象,最後它搖身一變成為了一個 Square 或 Rectangle 對象,並且表現出了相對應的行為。

package mainimport "fmt"type stockPosition struct {ticker     stringsharePrice float32count      float32}/* method to determine the value of a stock position */func (s stockPosition) getValue() float32 {return s.sharePrice * s.count}type car struct {make  stringmodel stringprice float32}/* method to determine the value of a car */func (c car) getValue() float32 {return c.price}/* contract that defines different things that have value */type valuable interface {getValue() float32}func showValue(asset valuable) {fmt.Printf("Value of the asset is %f\n", asset.getValue())}func main() {var o valuable = stockPosition{"GOOG", 577.20, 4}showValue(o)o = car{"BMW", "M3", 66500}showValue(o)}

  資料類型實現了介面,就能使用以介面變數為參數的方法

備忘:

有的時候,也會以一種稍微不同的方式來使用介面這個詞:從某個類型的角度來看,它的介面指的是:它的所有匯出方法,只不過沒有顯式地為這些匯出方法額外定一個介面而已。

golang interface介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.