Go 1.18 introduced generics, bringing type parameters and constraints to the language. Understanding comparable, any, and the difference between generic functions and methods is essential for writing reusable, type-safe Go libraries.
0 / 5 completed
1 / 5
What does the comparable constraint enable in a Go generic function?
comparable is a built-in constraint that permits types that can be compared for equality using == and !=, which is required for use as map keys. It does not imply ordering (< or >).
2 / 5
In Go generics, what is the difference between any and interface{} as a type constraint?
any is an alias for interface{} introduced in Go 1.18. They are completely identical. any was added as a readability improvement and is preferred in modern Go code.
3 / 5
Why can a generic method in Go NOT introduce new type parameters that are not already on its receiver type?
Go requires that a generic method's type parameters come from the receiver's type declaration. This keeps interface satisfaction unambiguous — you know the full method signature without additional type arguments at the call site.
4 / 5
Given type Number interface { ~int | ~float64 }, what does the tilde (~) prefix mean?
The ~ (tilde) prefix in a union element means the constraint matches any type whose underlying type is the listed type. This allows custom named types like type MyInt int to satisfy the constraint.
5 / 5
You write func Map[T, U any](s []T, f func(T) U) []U. What prevents you from calling it as Map(nums, double) in most cases?
Go's type inference is powerful enough to deduce both T from the slice element type and U from the return type of the function argument. In practice Map(nums, double) works without explicit type parameters since Go 1.21.