Go conditional pointer value

Issue

I have a couple of structs in a program. I have a pointer that should conditionally point to one of these structs. Here is a short non-functioning example:

type Struct1 struct {
    name string
}
type Struct2 struct {
    name string
}

func main() {
    var outputDevice
    switch inputValue {
        case "one":
            outputDevice = &Struct1{name: "name"}
        case "two":
            outputDevice = &struct2{name: "name"}
    }
}

Note, both of the structs have a common interface:

type Output interface {
    Print() error
}

Any ideas about how to tackle this problem.

Solution

This is exactly what interfaces are for.

If your two types already share a common interface, than make your variable of the interface type:

var outputDevice Output

Answered By – meagar

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.