如何获得父嵌入式结构字段值? [英] How to get parent embedded struct field value?

查看:101
本文介绍了如何获得父嵌入式结构字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型动态结构{
Id字符串
//和一些更常见的字段
}

使用我的软件包的用户应该能够实现自己的 Animal s。由于我需要 Id 在我的一个方法中用户必须嵌入我的结构。

  type Dog struct {
Animal
Name string
Legs int
}

在我的包中,我有一个 save()函数,可以将 Animal s保存为数据库。因为我不知道用户的类型,我必须使用 interface {} 作为参数类型。我的问题是:如何获得 Id (来自父级结构 Animal )?目前我使用一些JSON解析和解组,但这是去/去的路吗?

  func put(doc接口{})错误{
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)//终于有了Id
// ...
}

用法

  func main(){
bello:=狗{
Animal:Animal {
Id :abcd1234,
},
名称:bello,
Legs:4,
}
err:= put(bello)
/ / ...
}


解决方案

可以添加一个接口以确保获得对父结构的引用:

  type AnimalGetter interface {
GetAnimal()* Animal
}

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

这样可以保存方法做一个类型断言(AnimalGetter):

$ p $ func save(obj interface {}){
animal:= obj。(AnimalGetter)
fmt.Printf(%v\\\
,animal.GetAnimal())
}

查看中的完整示例 play.golang.org



输出:

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

简单: p>

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

play.golang.org


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)
  // ...
}

解决方案

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\n", animal.GetAnimal())
}

See a complete example in play.golang.org.

Output:

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

Simpler:

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

(play.golang.org)

这篇关于如何获得父嵌入式结构字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆