What are generic type aliases (Go 1.24), and how do they differ from generic type definitions?
Question 142HardGo 1.22 to 1.25
A type definition, type Set[T comparable] map[T]struct{}, creates a new, distinct named type that can have methods. A type alias, type A = B, is just another name for the same type. Go 1.24 fully enabled parameterized aliases. Go 1.23 had them only behind GOEXPERIMENT=aliastypeparams.
// Go 1.24+
type Set[T comparable] = map[T]struct{} // alias: identical to map[T]struct{}
type Pairs[K comparable, V any] = []struct {
Key K
Val V
}
func main() {
var s Set[string] = map[string]struct{}{"go": {}}
var m map[string]struct{} = s // same type, no conversion needed
fmt.Println(len(m)) // 1
}
// Main use case: moving a generic type between packages without breaking users
// package old
// type List[T any] = newpkg.List[T]
Differences:
- You cannot declare methods on a generic alias at all ("cannot define new methods on generic alias type"). Methods belong to the aliased type, and a non-generic alias can carry methods only if the aliased type is a named type in the same package.
- Alias type parameters may have constraints, but the aliased type must be valid for all of them.
- Reflection and
%Tprint the underlying aliased type, not the alias name.
Interviewers mention this to check that you follow recent releases and understand large-scale refactoring with aliases, which is the reason aliases exist at all.
More on Generics
- Q140How do generics combine with Go 1.23 iterators (
iter.Seq)? Write lazyFilterandMapadapters and explain theyieldcontract. - Q141What is
iter.Pull, and when do you need it? Implement a genericZip. - Q143Are generic types covariant? Can a
Box[Dog]be used as aBox[Animal], or aBox[int]converted to aBox[MyInt]? - Q144What is an "instantiation cycle"? Why does this recursive generic function fail to compile?
- Q145What does this print? (
%Tand reflection on generic types) - Q146Write a generic fan-in
Mergefor channels. What are the concurrency pitfalls?