-1

Lets jump straight into a code snippet.

type Animal[T any] struct {
    Name string
    Type string
    Params T
}

type DogParams struct {
    TailLength int
}

type CatParams struct {
    MeowVolume int
}

type Dog = Animal[DogParams]
type Cat = Animal[CatParams]
type Tiger = Animal[CatParams]

var animals = []Animal[any]{
    {
        Name:   "biggie doggie",
        Type:   "dog",
        Params: DogParams{TailLength: 5},
    },
    {
        Name:   "persia",
        Type:   "cat",
        Params: CatParams{MeowVolume: 2},
    },
}

What is the best way to convert an animal from Animal[any] to Animal[CatParams] ?

I have tried

cat, ok := any(animals[1]).(Cat)

and it's not ok.

Thanks in advance!

bumber
  • 105
  • 1
  • 7
  • 1
    Basically there is no way (except doing it manually) Even with parametric polymorphism Go is still statically typed and there is no type conversion between any and DogParam. – Volker Oct 17 '22 at 04:50
  • 1
    You can cast to `Cat` only instances of type `Cat`. It is a named type, and by the rules of Go it is unique. No other types, event with the same fields, could be casted to it. That means, the anonympus type `Animal[any]` can't be casted to `Cat`. – Pak Uula Oct 17 '22 at 04:53

1 Answers1

0

Following the comments from @Volker and @Pak Uula, you can stick them in an interface{} slice, but this isn't run-time dynamic typing. A Cat is still a Cat:

var animals = []interface{}{
    Dog{
        Name:   "biggie doggie",
        Type:   "dog",
        Params: DogParams{TailLength: 5},
    },
    Cat{
        Name:   "persia",
        Type:   "cat",
        Params: CatParams{MeowVolume: 2},
    },
}
craigb
  • 1,081
  • 1
  • 9