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语言里定义的方法集的规则是:
从值的角度来看规则

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

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

从接收者的角度来看规则

Values Methods Receivers
(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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 01.{ 换行: Opening Brace Can't Be Placed on a Separate Lin...
    码农不器阅读 7,024评论 0 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,599评论 5 6
  • 雨,淅淅沥沥下了好久,这样的雨天最适合睡觉。不明白为什么?雨拍打窗子的声音明明是嘈杂的,心里却难得的安静。秋天了,...
    阳城鱼king阅读 4,292评论 2 1
  • 心中种种的的不安,好像有什么事情要发生,不知道怎么办,从来没有过的感觉,心里真的不是滋味,愿一切安好……
    想念也是幸福阅读 1,580评论 0 0

友情链接更多精彩内容