Home > OS >  Go conditional pointer value
Go conditional pointer value

Time:03-08

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.

CodePudding user response:

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
  • Related