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

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

structure pointer field on a map in Golang

问题

我想在地图中包含不同结构的指针字段,如下所示。(当然,下面的代码是无效的)

  1. type StructA struct {
  2. }
  3. type StructB struct {
  4. }
  5. mymap := map[string]*struct{}{
  6. "StructA": &StructA{},
  7. "StructB": &StructB{},
  8. }

请注意,你需要使用&符号来获取结构体的指针,并在每个结构体后面加上{}来创建实例。

英文:

I want to include different structure pointer fields in the map as shown below. (Of course the code below doesnt work)

  1. type StructA struct {
  2. }
  3. type StructB struct {
  4. }
  5. mymap := map[string]*struct{}{
  6. "StructA": StructA,
  7. "StructB": StructB,
  8. }

答案1

得分: 2

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

  1. mymap := map[string]interface{}{
  2. "StructA": StructA{},
  3. "StructB": StructB{},
  4. }

为了更安全一些,你可以限制可以添加到映射中的类型只能是这两个结构体。为此,你需要一个指定两个结构体类型都实现的函数的接口。

  1. type (
  2. Common interface{ ImplementsCommon() }
  3. A struct{}
  4. B struct{}
  5. )
  6. func (A) ImplementsCommon() {}
  7. func (B) ImplementsCommon() {}
  8. mymap := map[string]Common{
  9. "A": A{},
  10. "B": B{},
  11. }

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:

  1. mymap := map[string]inteface{}{
  2. "StructA": StructA{},
  3. "StructB": StructB{},
  4. }

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.

  1. type (
  2. Common interface{ ImplementsCommon() }
  3. A struct{}
  4. B struct{}
  5. )
  6. func (A) ImplementsCommon() {}
  7. func (B) ImplementsCommon() {}
  8. mymap := map[string]Common{
  9. "A": A{},
  10. "B": B{},
  11. }

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:

确定