go接口实现中,值接收者和指针接收者的区别

date
Jun 27, 2021
slug
49
status
Published
tags
Go
summary
type
Post
指针接收者必须通过地址方式赋值给接口.譬如Cat
package main

import (
	"fmt"
)

type AnimalInterface interface {
	bake(string) error
}

//Dog ...
type Dog struct {
	name string
}

func (dog Dog) bake(w string) error {
	fmt.Printf("%s bake %s \n", dog.name, w)
	return nil
}

type Cat struct {
	name string
}

func (cat *Cat) bake(w string) error {
	fmt.Printf("%s bake %s \n", cat.name, w)
	return nil
}

func main() {

	var dogBig AnimalInterface = Dog{
		name: "大黄",
	}

	dogBig.bake("吴奇隆")

	var dogLittle AnimalInterface = &Dog{
		name: "小黄",
	}

	dogLittle.bake("李易峰")

	// cannot use Cat literal (type Cat) as type AnimalInterface in assignment:Cat does not implement AnimalInterface (bake method has pointer receiver)
	var catHua AnimalInterface = Cat{
		name: "小花",
	}

	catHua.bake("刘亦菲")

	var catBlue AnimalInterface = &Cat{
		name: "小蓝",
	}

	catBlue.bake("张园园")

}
https://blog.csdn.net/x356982611/article/details/106544801

© chaleaoch 2021