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 sendNotification(n notifier){
    n.notify()
}


func main(){
    u := user{"ethan","xxx@xx.com"}
    sendNotification(u)     //错误
    //sendNotification(&u)     //正确
}

上面的代码为notifier接口的实现,看似正常但是编译无法通过,报错信息是

cannot use u (type user) as type notifier in argument to sendNotification:
        user does not implement notifier (notify method has pointer receiver)
func (u *user) notify()sendNotification
方法接收者
T (t T)
*T (t T) and (t *T)
  • T类型的值的方法集只包含值接收者声明的方法。
  • 指向T类型的指针的方法集既包含值接收者声明的方法,也包含指针接收者声明的方法。
方法接收者
(t T) (t T) and (t *T)
(t *T) (t *T)
  • 通过《go语言实战》中第五章的5.4节“接口”学习到以上接口实现的细节,记录一下学习笔记。

欢迎关注我们的微信公众号,每天学习Go知识