从接收者类型的角度来看方法集

//从接收者类型的角度来看方法集
Methods Receivers   Values
(t T)           	T and *T
(t *T)				*T
如果使用指针接收者来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。
如果使用值接收者来实现一个接口,那么那个类型的值和指针都能够实现对应的接口
// 示例
package main
import (
	"fmt"
)
// 定义接口
type notifier interface{
    notify()
}
// 定义user结构体
type user struct{
    name string
    email string
}
// 使用指针接收者实现的方法
func (u *user) notify(){
    fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}
//sendNotification接收一个实现了notifier接口的值
func sendNotification(n notifier){
    n.notify()
}

// 应用程序入口
func main(){
    // 创建一个user类型的值
    u := user{"Bill", "bill@email.com"}
    //sendNotification(u)  // 这边会报错
    sendNotification(&u) // 正确写法传指针
}


示例:
// 使用值接收者
package main
type animal interface{
    move()
    eat(something string)
}
type cat struct{
    name string
    feet int8
}

// 使用值接收者实现了接口的所有方法
func (c cat) move(){
    fmt.Println("走猫步")
}
func (c cat) eat(food string){
    fmt.Println("猫吃%s...\n", food)
}

func main(){
    var a1 animal
    c1 := cat{"tom",4} // cat
    c2 := &cat{"假老练", 4} //*cat
    
    a1 = c1 
    fmt.Println(a1) // {tom 4}
    a1 = c2
    fmt.Println(a1) //&{假老练 4}
}


//使用指针接收者
package main
type animal interface{
    move()
    eat(something string)
}
type cat struct{
    name string
    feet int8
}

// 使用指针接收者实现了接口的所有方法
func (c *cat) move(){
    fmt.Println("走猫步")
}
func (c *cat) eat(food string){
    fmt.Println("猫吃%s...\n", food)
}

func main(){
    var a1 animal
    c1 := cat{"tom",4} // cat
    c2 := &cat{"假老练", 4} //*cat
    
    //a1 = c1 //会报错:实现animal这个接口的是cat的指针类型
    a1 = &c1
    fmt.Println(a1) // {tom 4}
    a1 = c2
    fmt.Println(a1) //&{假老练 4}
}


// 使用值接收者实现接口与使用指针接收者实现接口的区别???
使用值接收者实现接口,结构体值类型和结构体指针类型的变量都能存,
使用指针接收者实现接口,只能是结构体指针类型的变量
posted @ 2021-10-29 15:11  我在路上回头看  阅读(49)  评论(0编辑  收藏  举报