英文:
structure pointer field on a map in Golang
问题
我想在地图中包含不同结构的指针字段,如下所示。(当然,下面的代码是无效的)
type StructA struct {
}
type StructB struct {
}
mymap := map[string]*struct{}{
"StructA": &StructA{},
"StructB": &StructB{},
}
请注意,你需要使用&
符号来获取结构体的指针,并在每个结构体后面加上{}
来创建实例。
英文:
I want to include different structure pointer fields in the map as shown below. (Of course the code below doesnt work)
type StructA struct {
}
type StructB struct {
}
mymap := map[string]*struct{}{
"StructA": StructA,
"StructB": StructB,
}
答案1
得分: 2
如@icza所说,映射的元素类型必须是特定类型。但是,这可以是一个可以存储不同类型对象的接口。类型any
(interface{}
的别名)在某种程度上类似于指针(尽管它还存储类型信息),因此你可以这样做:
mymap := map[string]interface{}{
"StructA": StructA{},
"StructB": StructB{},
}
为了更安全一些,你可以限制可以添加到映射中的类型只能是这两个结构体。为此,你需要一个指定两个结构体类型都实现的函数的接口。
type (
Common interface{ ImplementsCommon() }
A struct{}
B struct{}
)
func (A) ImplementsCommon() {}
func (B) ImplementsCommon() {}
mymap := map[string]Common{
"A": A{},
"B": B{},
}
在Go Playground上试一试。
英文:
As @icza said the element type of a map must be a specific type. But this could be an interface that can store an object of different types. The type any
(an alias for interface{}
is in some ways like a pointer (though it also stores type info), so you could just do:
mymap := map[string]inteface{}{
"StructA": StructA{},
"StructB": StructB{},
}
To be a little safer you can restrict the types that can be added to the map to just the two structs. To do this you need an interface which specifies a function that both the struct types implement.
type (
Common interface{ ImplementsCommon() }
A struct{}
B struct{}
)
func (A) ImplementsCommon() {}
func (B) ImplementsCommon() {}
mymap := map[string]Common{
"A": A{},
"B": B{},
}
Try it on the Go Playground
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论