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条)

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。