1

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?

1
  • Yes, let me amend that Commented Jan 24 at 3:42

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.