在Golang中,可以使用结构指针字段来定义一个映射(map)。

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

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所说,映射的元素类型必须是特定类型。但是,这可以是一个可以存储不同类型对象的接口。类型anyinterface{}的别名)在某种程度上类似于指针(尽管它还存储类型信息),因此你可以这样做:

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

huangapple
  • 本文由 发表于 2022年6月13日 16:55:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/72600147.html
匿名

发表评论

匿名网友

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

确定