Go条件指针值

huangapple go评论66阅读模式
英文:

Go conditional pointer value

问题

我在程序中有几个结构体。我有一个指针,应该根据条件指向其中一个结构体。这是一个简短的非功能示例:

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"}
    }
}

请注意,这两个结构体都有一个共同的接口:

type Output interface {
    Print() error
}

有关如何解决这个问题的任何想法吗?

英文:

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.

答案1

得分: 1

这正是接口的用途。

如果你的两种类型已经共享一个公共接口,那么将你的变量声明为接口类型:

var outputDevice Output
英文:

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

huangapple
  • 本文由 发表于 2022年3月8日 06:54:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71388176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定