Can I construct a slice of a generic type with different type parameters?

No.

Given a parametrized Token type as:

type Token[T any] struct {
    TokenType string
    Literal   T
}

each instantiation with a different type argument produces a different (named) type.

In other words, Token[string] is not assignable to Token[int]. Nor is it assignable to Token[any] as any here is used as a static type to instantiate T.

So when you construct a slice with a specific instance of Token[T any], different instances are simply not assignable to its element type:

tokS := []*Token[string]{tok1, tok2}
// invalid: cannot use tok2 (variable of type *Token[int]) as type *Token[string] in array or slice literal

The only slice that can hold different types, as Token[string] and Token[int] is []interface{} or []any.


since we wouldn’t be able to infer a type for the Slice of tokens. Is this assumption correct?

Almost. More precisely, the slice of Token wouldn’t infer anything because you yourself must construct it with a concrete instantiation of the generic type

Type inference is used to deduce missing type parameters from those already supplied for function arguments. Generic types must be explicitly instantiated, with a concrete type argument for each type parameter.

Leave a Comment