2018-03-15 02:13
浏览 30

如何在Go中将struct方法访问到嵌入式方法? [重复]

This question already has an answer here:

Using inheritance in Python

class Animal(object):
    def eat(self):
        print + " is eating " + self.get_food_type()

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

    def get_food_type(self):
        return "dog food"

dog = Dog("Brian")

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

UPDATE: In the example above, my sub class is calling a method from its super class and the function in super class is actually aware of the sub class methods. I want to be able to accomplish a similar effect in Go.

The closest I can get with inheritance is struct embedding in Go.

type Animal struct {
    Name string

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

type Dog struct {

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

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

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

Apologize for the previous mistake, I realized struct field was indeed better to be put into the Animal struct because all animals share the attribute name. However, I want different implementation of the same method across different struct that embeds the Animal struct.


1条回答 默认 最新

相关推荐 更多相似问题