Go

What does this print? (type switch on a type parameter)

Question 123MediumGo 1.22 to 1.25
type MyInt int

func Describe[T any](v T) string {
    switch any(v).(type) {
    case int:
        return "int"
    case fmt.Stringer:
        return "Stringer"
    default:
        return "other"
    }
}

func main() {
    fmt.Println(Describe(42), Describe(MyInt(1)), Describe[any](3), Describe(time.Second))
}

Output: int other int Stringer

  • You cannot type-switch or type-assert on a type-parameter value directly. v.(int) fails with "cannot use type switch on type parameter value", so you convert to any first.
  • MyInt is not int. Type switches match exact dynamic types, not underlying types, and MyInt has no String method, so the result is other.
  • Describe[any](3): T is any, so v is an interface holding int. Its dynamic type is int.
  • time.Duration has String(), so it matches fmt.Stringer.

Also be ready for the design point: type-switching inside generic code is often a smell. If you branch per type, you probably want an interface, or separate functions.

More on Generics

All 36 Generics questions