用接口构造函数替换结构体问题

问题描述 投票:0回答:1

我有这个示例代码:

// 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)

我做错了什么以及我应该怎么做?

go interface
1个回答
0
投票

您尝试使用接口和结构来表示狗和猫等动物,并且希望为它们定义一个通用接口。以下是对您的代码的一些更正:

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 接口。

注:

  • 在 Go 中使用组合而不是继承。
  • 在具体类型上定义方法来满足接口,而不是嵌入接口本身。
  • 从工厂函数返回实现接口的具体类型。
© www.soinside.com 2019 - 2024. All rights reserved.