Home > Net >  structure pointer field on a map in Golang
structure pointer field on a map in Golang

Time:06-14

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

CodePudding user response:

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

  •  Tags:  
  • go
  • Related