0

https://github.com/google/jsonapi/blob/master/node.go

The structs OnePayload and ManyPayload, in the link above, have common fields:

Data
Included
Links
Meta

I want to write a method which takes either OnePayload or ManyPayload as an argument and assign values to Links and Meta as follows:

func DoSomething(payload interface{}) {
    ...
    payload.Links = links
    payload.Meta = meta
}

But I get the following error:

payload.Links undefined (type interface{} has no field or method Links)
payload.Meta undefined (type interface{} has no field or method Meta)

Could you advise how to represent OnePayload and ManyPayload using a common interface please?

MAK
  • 1,915
  • 4
  • 20
  • 44

1 Answers1

1

You can use reflection:

func main() {
    op := OnePayload{}
    DoSomething(&op)
    fmt.Print(op)
}

func DoSomething(payload interface{}) {
    exampleLink := Links{}
    link := reflect.New(reflect.TypeOf(exampleLink))
    link.Elem().Set(reflect.ValueOf(exampleLink))

    reflect.ValueOf(payload).Elem().FieldByName("Links").Set(link)

}
Nickson Thanda
  • 799
  • 7
  • 11
  • Thank you. v.Links = links & v.Meta = meta - these two lines are repeated in both the cases. Suppose if there are 10 cases, they should be repeated 10 times. Could you advise how to avoid these duplicate lines please? – MAK Feb 26 '20 at 11:05
  • Can we use same body for two switch cases in Golang? – MAK Feb 26 '20 at 11:19
  • 1
    You can't combine the two switch cases like `case OnePayload, ManyPayload:` unfortunately, because it won't narrow down the type of the variable, so you will end up with the same error in your question – Nickson Thanda Feb 26 '20 at 11:48
  • I've updated the answer which I believe is what you're looking forward compared to the previous answer. – Nickson Thanda Feb 27 '20 at 15:19