国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

從 Golang中 method has pointer receiverd 異常去理解interface機(jī)制

2019-11-10 22:04:44
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在Golang中第一次使用interface 遇到了一個(gè)有意思的問(wèn)題:

method has pointer receiverd

這個(gè)問(wèn)題很普遍,所以在此記錄先來(lái)。 先看以下例子:

package mainimport ( "fmt")// notifier is an interface that defined// type behavior.type notifier interface { notify()}// user defines a user in the PRogram.type user struct { name string email string}// notify implements a method with a poifunc (u *user) notify() { fmt.Printf("Sending user email to %s“,u.name)}// main is the entry point for the applifunc main() { // Create a value of type User and s u := user{"Bill", "bill@email.com"} sendNotification(u)}func sendNotification(n notifier) { n.notify()}

運(yùn)行以上代碼,會(huì)得到一個(gè)這樣的錯(cuò)誤:

./listing36.go:32: cannot use u (type user) as type notifier in argument to sendNotification:user does not implement notifier (notify method has pointer receiver)

為了解決這個(gè)問(wèn)題,首先得先了解一下Golang 中 方法的集合的概念,一個(gè)struct雖然可以通過(guò)值類型和引用類型兩種方式定義方法,但是不通的對(duì)象類型對(duì)應(yīng)了不同的方法集:

Values Methods Receivers----------------------------------------------- T (t T)*T (t T) and (t *T)

值類型的對(duì)象只有(t T) 結(jié)構(gòu)的方法,雖然值類型的對(duì)象也可以調(diào)用(t *T) 方法,但這實(shí)際上是Golang編譯器自動(dòng)轉(zhuǎn)化成了&t的形式來(lái)調(diào)用方法,并不是表明值類型的對(duì)象擁有該方法。

換一個(gè)維度來(lái)看上面的表格可能更加直觀:

Methods Receivers Values-----------------------------------------------(t T) T and *T(t *T) *T

這就意味著指針類型的receiver 方法實(shí)現(xiàn)接口時(shí),只有指針類型的對(duì)象實(shí)現(xiàn)了該接口。

對(duì)應(yīng)上面的例子來(lái)說(shuō),只有&user實(shí)現(xiàn)了notifier接口,而user根本沒(méi)有實(shí)現(xiàn)該接口。所以上面代碼會(huì)報(bào)出這樣的異常。

notify method has pointer receiver

解決這個(gè)問(wèn)題也很容易,直接使用&user去代替user調(diào)用方法即可:

func main() { // Create a value of type User and send a notification. u := user{"Bill", "bill@email.com"} sendNotification(&u) // PASSED THE ADDRESS AND NO MORE ERROR.}

希望我通過(guò)這個(gè)異常,更深入的了解了Golang的interface機(jī)制。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 攀枝花市| 谷城县| 台南县| 习水县| 新宁县| 霍邱县| 柳林县| 望都县| 吉木萨尔县| 潍坊市| 赤城县| 广饶县| 武山县| 灵宝市| 平泉县| 伊通| 阿城市| 广东省| 嘉峪关市| 丰镇市| 龙江县| 七台河市| 临沭县| 资溪县| 东安县| 星子县| 东港市| 称多县| 惠东县| 娄烦县| 双峰县| 平谷区| 东源县| 黎城县| 金乡县| 阳西县| 昆山市| 阳原县| 双流县| 修文县| 天等县|