dictionarygostructinterfaceconstants

Struct field with multiple const types


Say I have a const type and corresponding sub types -

type Animaltype int32 
const ( 
    dogs  Animaltype = iota 
    cats
) 

type dogtype int32 
const ( 
    retriever dogtype = iota 
    whippet 
)

type cattype int32 
const ( 
    siamese cattype = iota 
    tabby 
)

I'd like a structure that holds the animal type and then a field that flexibly holds the subtype

type AnimalCount struct {
  category Animaltype
  subcategory map[dogtype]int32
}

But where I have dogtype for sub category I'd like it to be dogtype or cattype. For eg here I have I would be mapping the subtype to the count of that type

Is this possible in go?


Solution

  • You can do this with a union interface and generics.

    // Declare a type which is both cats and dogs
    type pettype interface {
        cattype | dogtype
    }
    
    // Declare AnimalCount using the union type.
    type AnimalCount[T pettype] struct {
      category Animaltype
      subcategory map[T]int32
    }
    
    func main() {
        // Instantiate AnimalCount with a concrete type.
        dc := AnimalCount[dogtype]{category: dogs, subcategory: map[dogtype]int32{retriever: 2, whippet: 4}}
        cc := AnimalCount[cattype]{category: cats, subcategory: map[cattype]int32{siamese: 5, tabby: 10}}
        fmt.Println("{}", dc)
        fmt.Println("{}", cc)
    }