英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论