Go

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 %T print 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

All 36 Generics questions