douzhang1115 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条回答 默认 最新

  • dongxuandong2045 2018-03-15 03:02

    Design your Go program to use composition rather than inheritance.

    In your example, why don't you want Animal to have a name? This will print: "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 {
    func main() {
        dog := &Dog{Animal{"Brian"}}

    You might find this related blog post on composition in Go useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



    • ¥15 二分类改为多分类问题
    • ¥15 Unity微信小游戏上调用ReadPixels()方法报错
    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?
    • ¥15 图论编程问题,有可以指导的吗
    • ¥15 DEA的CCR模型画图
    • ¥15 请假各位一个关于安卓车机的问题
    • ¥15 光谱仪怎么看这样的透射谱
    • ¥15 pyqt5 如何实现输入框输入关键词,下拉框显示模糊查询返回的结果?
    • ¥20 fluent模拟,可以燃烧和相变同时模拟吗?