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 toanyfirst. MyIntis notint. Type switches match exact dynamic types, not underlying types, and MyInt has no String method, so the result isother.Describe[any](3): T isany, so v is an interface holding int. Its dynamic type is int.time.DurationhasString(), so it matchesfmt.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
- Q121How do you get and check the zero value of a type parameter
T? - Q122What does this print? (nil checks inside generic code)
- Q124Why doesn't Go allow type parameters on methods? What do you do instead?
- Q125How do you write methods on a generic type? What is wrong with
func (s Stack[int]) Sum() int? - Q126Name the restrictions around type parameters: embedding, type declarations, and method sets.
- Q127Explain the "pointer method" constraint pattern (
PT interface{ *T; M() }). Why is it needed?