Go 1.27 Introduces Generic Methods

Go 1.27 Introduces Generic Methods

In March, I wrote about the proposal for generic methods - https://t.me/junsenior/332, and just two weeks ago, with the release of Go 1.27, it went live.

What this changes: previously, any method couldn't have generic parameters, for example:

type SomeStruct struct {
 intField int
}
 
// syntax error
func (s SomeStruct) Map[U any](mapFunc func(int) U) U {
 return mapFunc(s.intField)
}

Instead of methods, if you needed to attach a method with a generic type to a type, regular functions were created:

func Map[U any](s SomeStruct, mapFunc func (int) U) U {
 return mapFunc(s.intField)
}

Now, the example above is fully valid for any methods, not just for structs. And now such methods have unlocked method chaining for us:

type Box[T any] struct {
    val T
}
 
func (b Box[T]) Map[U any](mapFunc func(T) U) Box[U] {
    return Box[U]{val: mapFunc(b.val)}
}
 
b := Box[int]{val: 42}
 
res := b.Map(strconv.Itoa).
  Map(func(s string) string { 
      return "user-" + s 
   }).
  Map(strings.ToUpper)
 
// USER-42
fmt.Printf("%#v\n", res)   

In the math/rand/v2 package, you can already find an example:

func (r *Rand) N[Int intType](n Int) Int {
    if n <= 0 {
        panic("invalid argument to N")
    }
 
    return Int(r.uint64n(uint64(n)))
}

And in 1.26, instead of it, there was a regular function in the package:

func N[Int intType](n Int) Int {
 if n <= 0 {
  panic("invalid argument to N")
 }
 return Int(globalRand.uint64n(uint64(n)))
}

As we remember, this proposal really stirred up the community: both in the comments on GitHub and in threads on Reddit, but nevertheless - it was delivered. From denial, I came to realize that generics, globally, make code more convenient if applied correctly - I've seen several projects where they fit very well. Adding methods to them, since generics themselves have been in the language for many years already, is the right decision. It was necessary either not to introduce generics at all or, if introduced, to refine them.

Overall, the 1.27 release turned out to be interesting. Besides generic methods, Go now has uuid implemented within the stdlib, encoding/json/v2 was introduced - now unmarshalling works much faster, and there's much more new stuff. You can check out this and other updates in a clear and interactive way here: https://golang.guide/go-1-27/

And when almost all the code is written by AI - it's important to keep track and understand what's happening in the language and the tools we work with: at the very least - AI won't always have time to answer in an interview, and at most - code needs to be reviewed and understood, otherwise any project will quickly descend into an unsupported neural mess 🏁