Go接口實(shí)例

Go支持在struct類型上定義的方法。area方法有一個(gè)* rect類型的接收器??梢詾橹羔樆蛑到邮掌黝愋投x方法。這里是一個(gè)值接收器的例子。

這里調(diào)用struct定義的2個(gè)方法。

接口是方法簽名的命名集合。這里是幾何形狀(geometry)的基本接口。

對(duì)于這個(gè)例子,將在rect和circle類型上實(shí)現(xiàn)這個(gè)接口。

要在Go中實(shí)現(xiàn)一個(gè)接口,需要實(shí)現(xiàn)接口中的所有方法。 這里在rect上實(shí)現(xiàn)geometry的一個(gè)實(shí)例。

以及circles的實(shí)現(xiàn)。

如果變量具有接口類型,那么可以調(diào)用命名接口中的方法。這里是一個(gè)通用measure()函數(shù),任何幾何形狀都有這個(gè)函數(shù)。

circle和rect結(jié)構(gòu)類型都實(shí)現(xiàn)了幾何(geometry)接口,因此可以使用這些結(jié)構(gòu)體的實(shí)例上調(diào)用measure()函數(shù)。

代碼示例:

package main

import (

"fmt"

"math"

)

//定義幾何圖形的基本接口 geometry 幾何

type geometry interface {

area() float64

perim() float64

}

//定義矩形和圓形的結(jié)構(gòu)體

type rect struct {

width, height float64

}

type circle struct {

radius float64

}

//在GO中實(shí)現(xiàn)一個(gè)接口,只需要實(shí)現(xiàn)接口中的所有方法

//實(shí)現(xiàn)矩形的接口

//計(jì)算矩形的面積

func (r rect) area() float64 {

return r.width * r.height

}

//計(jì)算矩形的邊長

func (r rect) perim() float64 {

return r.width*2 + r.height*2

}

//實(shí)現(xiàn)幾何 圓 面積計(jì)算

func (c circle) area() float64 {

//圓周率 乘以 變徑的平方

return math.Pi * c.radius * c.radius

}

//計(jì)算圓的邊長

func (c circle) perim() float64 {

return 2 * math.Pi * c.radius

}

//如果變量有接口類型,那么我們可以調(diào)用命名接口中的方法。這里有一個(gè)通用的'measure'函數(shù)利用這一點(diǎn)來處理任何'geometry' 接口實(shí)現(xiàn)。

func measure(g geometry) {

fmt.Println(g)

fmt.Println(g.area())

fmt.Println(g.perim())

}

func main() {

r := rect{width: 3, height: 4}

c := circle{radius: 1}

// The `circle` and `rect` struct types both

// implement the `geometry` interface so we can use

// instances of

// these structs as arguments to `measure`.

measure(r)

measure(c)

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容