donglugou6652 2017-11-13 11:01
浏览 42


I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:

package main

type Animal struct{}
type Dog struct {
    Color string

type Person struct {
    Name string
    Age  int
    Pet  *Animal

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}

This is causing a compilation error:

cannot use dog (type *Dog) as type *Animal in field value

What is the correct way to go about doing an abstraction like this? Is it possible in Go?

End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.

To visualize, something like:

type Person struct {
    Name string
    Age  int
    Pet  *Dog OR *Cat OR *Hamster

Go Playground Link

  • 写回答



      相关推荐 更多相似问题


      • ¥15 如何在微信支付V3PHP版请求中添加header?
      • ¥15 在数字信号处理中用MATLAB显示波形。
      • ¥15 keil MDK软件进行仿真调试的局限
      • ¥15 关于gateway产生临时文件夹的问题
      • ¥15 Java Broken Pipe以及OOM
      • ¥20 请问有没有RTL8211FS的参考原理图
      • ¥50 esp32的platfromio工程添加文件就会编译失败
      • ¥15 linux下运行VASP报错
      • ¥15 python里面查找赋值,如何可以在剩余未空值的行里面进行进一步的筛选呢?
      • ¥15 电路分析的综合实验有没有会的