teone
teone

Reputation: 2183

How to define dynamic interface/struct

I'm pretty new to Go and really looking for some guidance.

In my application I have a channel that receives events, I'd like to have an interface like:

{
  "type": "event1",
  "data": {}
}

where the structure of data depends on the type.

Then the code that listen for those events in the channel will know what kind of structure to expect based on the type of the event.

How can I define such interface? Is that considered a good practice in Go?

Thanks in advance

Upvotes: 2

Views: 101

Answers (1)

poy
poy

Reputation: 10527

You are looking for a type switch:

package main

import (
    "fmt"
)

type X struct {
    i int
}

func main() {
    c := make(chan interface{}, 5)
    c <- 4
    c <- "hi"
    c <- X{}
    close(c)

    for value := range c {
        switch v := value.(type) {
        case int:
            fmt.Println("got int", v)
        case string:
            fmt.Println("got string", v)
        case X:
            fmt.Println("got X", v)
        default:
            fmt.Printf("unexpected type %T\n", value)
        }
    }
}

Upvotes: 3

Related Questions