Can struct member accept dynamic variable?

  Kiến thức lập trình

I have multiple struct. My main response struct is called WsPayload and it has a member variable called Payload. The Payload can either my Earthquake struct or the EventReport struct.

My question: How can I define my WsPayload Payload member variable so, it can accept both of my struct? is there a dynamic variable that I can use in Go to accomplish this.

type WsPayload struct {
    Action   string              `json: "action"`
    Message  string              `json: "message"`
    Etype    string              `json: "etype"`
    Payload  EventReport         `json: "payload"`.  //<---
    Conn     WebSocketConnection `json: "-"`
}

type Earthquake struct {
    Body     string `json: "body"`
    Location string `json: "location"`
    Rate     int    `json: "rate_earthquake"`
    Date     string `json: "lat"`
    Time     string `json: "lng"`
}

type EventReport struct {
    Title string   `json: "title"`
    Body  string   `json: "body"`
    Date  string   `json: "date"`
    Time  string   `json: "time"`
    Type  string   `json: "type"`
    Id    string   `json: "id"`
    Photo []string `json: "photo"`
}

At the moment, I can only define one struct at a time inside my WsPayload.

LEAVE A COMMENT