Skip to main content

Golang Generic Type Aliases

·161 words·1 min·

As of Go 1.24 , Go supports generic type aliases. It’s now possible to use generics with aliases.

package main

import "fmt"

type oldUser[T any] struct {
  ID   T
  Name string
}

func (u oldUser[T]) AboutMe() string {
  return fmt.Sprintf("Hi, my name is %s and my ID is %v", u.Name, u.ID)
}

// This is possible since go 1.24.
type newUser[T any] = oldUser[T]

func main() {
  intUser := newUser[int32]{
    ID:   1,
    Name: "Peter Integer",
  }
  stringUser := newUser[string]{
    ID:   "a",
    Name: "Peter String",
  }

  type customID struct {
    ID string
  }
  customUser := newUser[customID]{
    ID:   customID{ID: "a"},
    Name: "Peter Struct",
  }

  fmt.Println(intUser.AboutMe())
  fmt.Println(stringUser.AboutMe())
  fmt.Println(customUser.AboutMe())
}
Hi, my name is Peter Integer and my ID is 1
Hi, my name is Peter String and my ID is a
Hi, my name is Peter Struct and my ID is {a}

The repo with this example can be found here: