如何将 struct 方法的访问权限授予 Go 中的嵌入式方法?

How to give access of struct method to an embedded method in Go?

在Python

中使用继承
class Animal(object):
    def eat(self):
        print self.name + " is eating " + self.get_food_type()


class Dog(Animal):
    def __init__(self, name):
        self.name = name

    def get_food_type(self):
        return "dog food"

dog = Dog("Brian")
dog.eat()

# Expected output => "Brian is eating dog food"

更新:在上面的例子中,我的 sub class 从它的 super class 调用一个方法,而 super class 中的函数实际上知道 sub class 方法。我希望能够在 Go 中实现类似的效果。

我能得到的最接近继承的是 Go 中的结构嵌入。

type Animal struct {
    Name string
}

func (a *Animal) Eat() {
    fmt.Println(a.Name + " is eating " + a.GetFoodType())
}

type Dog struct {
    *Animal
}

func (d *Dog) GetFoodType() string {
    return "dog food"
}

func main() {
    dog := &Dog{&Animal{"Brian"}}
    dog.Eat()
}

# Error => type *Animal has no field or method GetFoodType

为之前的错误道歉,我意识到结构字段确实更好地放入 Animal 结构中,因为所有动物共享属性名称。但是,我希望在嵌入 Animal 结构的不同结构中对同一方法进行不同的实现。

设计您的 Go 程序以使用组合而不是继承。

在你的例子中,你为什么不希望 Animal 有名字?这将打印:"Brian is eating":

package main

import "fmt"

type Animal struct {
    Name    string
}

func (a *Animal) Eat() {
    fmt.Println(a.Name + " is eating")
}

type Dog struct {
    Animal
}

func main() {
    dog := &Dog{Animal{"Brian"}}
    dog.Eat()
}

您可能会发现 this related blog post 关于 Go 中的组合很有用。