Cannot infer T , generics multiple types

Viewed 109
func CreateSlice[T int | string](length int) []T {
    return make([]T, length)
}

Try to learn go and want to play with slices and generics . Above you can see that I want to say T can be or int or string => T int | string . Compiler say nothing about this case when I create this function , but on the moment I call it , it says cannot infer T

slices.CreateSlice(10)

Is there any restriction , or do I make some mistaces in syntax ?

1 Answers

The compiler cannot determine T from slices.CreateSlice(10) because T is not used as an argument. Fix by specifying T explicitly:

 slices.CreateSlice[int](10)    // evaluates to []int with len(10)
 slices.CreateSlice[string](10) // evaluates to []string with len(10)
Related