Type parameters
A function can be shared across types without losing the check at compile time.
Before generics, a shared function for []int and []string was written through any and type assertions, or copied twice. A type parameter leaves the check to the compiler:
func First[T any](items []T) T {
var zero T
if len(items) == 0 {
return zero
}
return items[0]
}
T is the name of the parameter. The constraint any means "any type". The call First([]int{4, 9}) infers T as int by itself. You write First[int](...) only when there is nothing to infer the type from.
The zero value of an arbitrary type is obtained with var zero T. For int that is 0, for string an empty string, for a slice nil. Returning "zero and a flag of whether the element was there" is sometimes more honest than a silent zero: zero can be a real first element. In this lesson the contract is simple: an empty input gives the zero of the type.
A generic is not slower than an ordinary function "because it is a template". The compiler generates code for the concrete types. Do not hide behavior inside a type parameter. "Knows how to save itself" is an interface with a method. "A slice of anything, take the first" is a type parameter. If inside the function you needed a switch on T, the generic probably does not fit.
Practice
Type inference
Do you need to write
First[int]([]int{1, 2})if the parameter is already a slice of int?- Yes, otherwise the code will not compile
- No, T will be inferred from the argument
- Yes, any turns off type inference
- Only in tests
The first element
Write
First[T any](items []T) T. Return the first element. If the slice is empty, return the zero value of typeT.The wrong place
Inside a generic you had to write a
switchon the concrete typeT. What does that more likely say?- Everything is fine. That is what generics are for
- The function probably should not be a generic
- You need to add five more type parameters
- The compiler itself forbids a switch on T, so the code is always syntactically wrong already