Golang 的结构体的组合(实现java继承的特性)

参考解析

题目来源: 大疆

答案:

  1. golang 通过结构体嵌套实现继承的特性
    在Go语言里,没有面向对象这个概念,自然就没有继承,但它支持结构体组合;
    你可以通过在结构体内嵌套结构体实现组合;
  1. type animal struct {
  2. name string
  3. age string
  4. }
  5. type cat struct {
  6. animal
  7. sound string
  8. }
  9. type dog struct {
  10. animal
  11. color string
  12. }

2. 使用

  1. cat := cat{
  2. animal: animal{
  3. name: "xiaomiao",
  4. age: "1",
  5. },
  6. sound: "miaomiaomiao",
  7. }
  8. dog := dog{
  9. animal: animal{
  10. name: "dahuang",
  11. age: "2",
  12. },
  13. color: "yellow",
  14. }