Constraints: comparable and interfaces
Union constraints and the comparable built-in
What is a constraint?
A constraint restricts which types can be used as a type argument. Without a constraint, the type parameter is any (the empty interface — only supports assignment and comparison via ==).
The any constraint
any (alias for interface{}) is the widest constraint — all types satisfy it. You can only use operations all types support: assignment and passing to interface parameters.
func Print[T any](v T) { fmt.Println(v) }All lessons in this course
- Type Parameters Syntax
- Constraints: comparable and interfaces
- Generic Data Structures
- Generics in Practice: Pitfalls