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

Inheritance 如何将struct方法的访问权授予Go中的嵌入式方法?,inheritance,go,composition,Inheritance,Go,Composition,在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"

在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"
更新:在上面的例子中,我的子类正在从它的超类调用一个方法,而超类中的函数实际上知道子类方法。我希望能够在围棋中实现类似的效果

我能从继承中得到的最接近的方法是在Go中嵌入struct

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

为前面的错误道歉,我意识到struct字段确实最好放在
Animal
struct中,因为所有动物都共享属性名。但是,我希望在嵌入
动物
结构的不同结构中实现相同方法。

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

在您的示例中,为什么不希望动物有一个名称?这将打印:“布赖恩正在吃”:


您可能会发现Go中的on composition很有用。

设计您的Go程序以使用composition而不是继承

在您的示例中,为什么不希望动物有一个名称?这将打印:“布赖恩正在吃”:


您可能会在Go中找到关于合成的有用信息。

在本例中,由于
动物
使用
名称
,因此将该字段放在
动物
中而不是
似乎是有意义的。
Animal
方法所需的任何内容都必须可以从
Animal
本身访问,因为无法从这些方法访问嵌入
Animal
的结构的其余部分。在本例中,由于
Animal
使用
名称,因此可能存在重复,将该字段放在
Animal
而不是
Dog
中似乎是有意义的。
Animal
方法所需的任何内容都必须可以从
Animal
本身访问,因为无法从这些方法访问嵌入
Animal
的结构的其余部分。与
func(动物)Eat()和Dog{Animal{Brian}
一起使用。很好的示例+1.1也适用于
func(动物)Eat()和Dog{Animal{“Brian”}
。好例子+1。
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()
}