美文网首页Go
Go的方法集

Go的方法集

作者: 不会写代码的程序猿 | 来源:发表于2017-06-23 17:04 被阅读0次

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

    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)

    相关文章

      网友评论

        本文标题:Go的方法集

        本文链接:https://www.haomeiwen.com/subject/alvccxtx.html