dtqf81594 2014-09-08 14:10
浏览 5
已采纳

如何获得父嵌入的struct字段值?

I have the following struct in my package.

type Animal struct {
  Id string
  // and some more common fields
}

A user who uses my package should be able to implement own Animals. As I need Id in one of my methods the user has to embed my struct.

type Dog struct {
  Animal
  Name string
  Legs int
}

In my package I have a save() function that saves Animals to database. As I don't know the user's type I have to use interface{} as argument type. My question is: How do I get the Id (from the parent struct Animal)? At the moment I use some JSON parsing and unmarshalling, but is this the way to go/Go?

func put(doc interface{}) error {
  res, err := json.Marshal(doc)
  if err != nil {
    return err
  }
  var animal *Animal
  err = json.Unmarshal(res, &animal)
  if err != nil {
    return err
  }
  fmt.Println(animal.Id) // finally I have the Id
  // ...
}

Usage

func main() {
  bello := Dog{
    Animal: Animal{
      Id: "abcd1234",
    },
    Name: "bello",
    Legs: 4,
  }
  err := put(bello)
  // ...
}
  • 写回答

3条回答 默认 最新

  • duanmei1536 2014-09-08 14:20
    关注

    Maybe you can add an interface in order to be sure to get a reference to the parent struct:

    type AnimalGetter interface {
        GetAnimal() *Animal
    }
    
    func (dog *Dog) GetAnimal() *Animal {
        return &dog.Animal
    }
    

    That would allow your save method to do a type assertion (AnimalGetter):

    func save(obj interface{}) {
        animal := obj.(AnimalGetter)
        fmt.Printf("%v
    ", animal.GetAnimal())
    }
    

    See a complete example in <kbd>play.golang.org</kbd>.

    Output:

    &{{dogid} wouf 0}
    &{dogid}
    

    Simpler:

    func save(animal AnimalGetter) {
        fmt.Printf("%v
    ", animal.GetAnimal())
    }
    

    (<kbd>play.golang.org</kbd>)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备