donglugou6652 2017-11-13 11:01
浏览 42
已采纳

在Go中实现Struct抽象的正确方法是什么?

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

  • 写回答

2条回答 默认 最新

  • dousi5358 2017-11-13 11:25
    关注

    Two working samples:

    1- Try this:

    package main
    
    import (
        "fmt"
    )
    
    type Animal interface {
        color() string
    }
    type Dog struct {
        Color string
    }
    
    func (d Dog) color() string {
        return d.Color
    }
    
    type Person struct {
        Name string
        Age  int
        Pet  Animal
    }
    
    func main() {
        dog := &Dog{Color: "brown"}
        tom := &Person{Name: "Tom", Age: 13, Pet: dog}
        fmt.Println(tom.Pet.color())
    }
    

    2- Try this:

    package main
    
    import (
        "fmt"
    )
    
    type Animal struct{}
    type Dog struct {
        Animal
        Color string
    }
    
    type Person struct {
        Name string
        Age  int
        Pet  interface{}
    }
    
    func main() {
        dog := &Dog{Color: "brown"}
        tom := &Person{Name: "Tom", Age: 13, Pet: dog}
        fmt.Println(tom.Name)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算