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

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 {
    *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

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.

</div>
  • 写回答

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 {
        Animal
    }
    
    func main() {
        dog := &Dog{Animal{"Brian"}}
        dog.Eat()
    }
    

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

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题