Go的方法集

方法集定义了接口的接受规则。

package main

import "fmt"

type notifier interface {
    notify()
}

type user struct {
    name string
    email string
}

func (u *user) notify() {
    fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}

func main() {
    u := user{"Bill", "bill@email.com"}
    sendNotificatioin(u)
}

func sendNotificatioin(n notifier) {
    n.notify()
}

这段代码看起来是没问题的,但是无法通过编译的。

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

user类型的值没有实现notify接口。

Go语言里定义的方法集的规则是:
从值的角度来看规则

ValuesMethods Receivers
T (t T)
*T (t T) and (t *T)

T类型的值的方法集只包含值接收者声明的方法。而指向T类型的指针的方法集既包含值接收者声明的方法,也包含指针接收者声明的方法。

从接收者的角度来看规则

Methods ReceiversValues
(t T) T and *T
(t *T) *T

使用指针接收者来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。如果使用值接收者来实现一个接口,那么那个类型的值和指针都能够实现对应的接口。

例如:
①:func (u *user) notify() {
fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}
sendNotificatioin(&u)

②:func (u user) notify() {
fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}
sendNotificatioin(u)

③:func (u user) notify() {
fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}
sendNotificatioin(&u)



作者:不会写代码的程序猿
链接:https://www.jianshu.com/p/1a5c68fa4009
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

posted @ 2018-10-22 14:08  邱明成  阅读(993)  评论(0编辑  收藏  举报