gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:31:50 28 4
gpt4 key购买 nike

<分区>

在 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"

更新:在上面的例子中,我的子类从它的父类(super class)中调用一个方法,父类(super 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 结构的不同结构中对同一方法进行不同的实现。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com