Interface
type notifier interface {
notify()
}
type user struct {
name string
email string
}
func (u *user) notify() {
fmt.Printf("sending %v %v", u.email, u.name)
}
func sendNotification(n notifier) {
n.notify()
}
func main() {
u := user{name: "name", email: "email"}
sendNotification(&u)
}
代码中user实现了接口notify,但是编译执行时报错
cannot use u (type user) as type notifier in argument to sendNotification:
user does not implement notifier (notify method has pointer receiver)
为什么会这样呢?让我们看一下golang规范中的描述:
Values | Methods Receivers |
---|---|
T | (t T) |
*T |