在Golang中第一次使用interface 遇到了一個(gè)有意思的問題:
method has pointer receiverd這個(gè)問題很普遍,所以在此記錄先來。 先看以下例子:
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", "[email protected]"} 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è)問題,首先得先了解一下Golang 中 方法的集合的概念,一個(gè)struct雖然可以通過值類型和引用類型兩種方式定義方法,但是不通的對(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的形式來調(diào)用方法,并不是表明值類型的對(duì)象擁有該方法。
換一個(gè)維度來看上面的表格可能更加直觀:
Methods Receivers Values-----------------------------------------------(t T) T and *T(t *T) *T這就意味著指針類型的receiver 方法實(shí)現(xiàn)接口時(shí),只有指針類型的對(duì)象實(shí)現(xiàn)了該接口。
對(duì)應(yīng)上面的例子來說,只有&user實(shí)現(xiàn)了notifier接口,而user根本沒有實(shí)現(xiàn)該接口。所以上面代碼會(huì)報(bào)出這樣的異常。
notify method has pointer receiver解決這個(gè)問題也很容易,直接使用&user去代替user調(diào)用方法即可:
func main() { // Create a value of type User and send a notification. u := user{"Bill", "[email protected]"} sendNotification(&u) // PASSED THE ADDRESS AND NO MORE ERROR.}希望我通過這個(gè)異常,更深入的了解了Golang的interface機(jī)制。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注