我有这个示例代码:
// scene.go
var (
animal *Dog
)
func Init() {
animal = NewDog()
}
// dog.go
typedef Dog struct {
name string
}
func (d *Dog) Attack() {}
func NewDog() *Dog {
dog := new(Dog)
retutn dog
}
我想实现 Cat 与 Dog 具有相同的公共接口,区分 Animal 接口
// animal.go -- new file
type Animal interface {
Attack()
}
// scene.go
var (
animal *Animal // was *Dog
)
// dog.go
typedef Dog struct {
Animal // added
name string
}
func (d *Dog) Attack() {}
func NewDog() *Animal { // changed *Dog to *Animal
dog := new(Dog)
return dog
}
但在这种情况下我收到错误
cannot use dog (variable of type *Dog) as *Animal value in return statement: *Dog does not implement *Animal (type *Animal is pointer to interface, not interface)
我做错了什么以及我应该怎么做?
您尝试使用接口和结构来表示狗和猫等动物,并且希望为它们定义一个通用接口。以下是对您的代码的一些更正:
var (
animal Animal // Change from *Animal to Animal
)
type Dog struct {
name string
}
func (d *Dog) Attack() {
// Implement attack behavior for Dog
}
func NewDog() Animal {
return &Dog{}
}
type Cat struct {
name string
}
func (c *Cat) Attack() {
// Implement attack behavior for Cat
}
func NewCat() Animal {
return &Cat{}
}
这样,Dog 和 Cat 类型都通过实现 Attack 方法来实现 Animal 接口。
注: