在Golang中第一次使用interface 遇到了一個有意思的問題:
method has pointer receiverd這個問題很普遍,所以在此記錄先來。 先看以下例子:
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()}運行以上代碼,會得到一個這樣的錯誤:
./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)為了解決這個問題,首先得先了解一下Golang 中 方法的集合的概念,一個struct雖然可以通過值類型和引用類型兩種方式定義方法,但是不通的對象類型對應了不同的方法集:
Values Methods Receivers----------------------------------------------- T (t T)*T (t T) and (t *T)值類型的對象只有(t T) 結構的方法,雖然值類型的對象也可以調用(t *T) 方法,但這實際上是Golang編譯器自動轉化成了&t的形式來調用方法,并不是表明值類型的對象擁有該方法。
換一個維度來看上面的表格可能更加直觀:
Methods Receivers Values-----------------------------------------------(t T) T and *T(t *T) *T這就意味著指針類型的receiver 方法實現接口時,只有指針類型的對象實現了該接口。
對應上面的例子來說,只有&user實現了notifier接口,而user根本沒有實現該接口。所以上面代碼會報出這樣的異常。
notify method has pointer receiver解決這個問題也很容易,直接使用&user去代替user調用方法即可:
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.}希望我通過這個異常,更深入的了解了Golang的interface機制。
新聞熱點
疑難解答