Plan generic methods for Go 1.27
Plan generic methods for Go 1.27
Go 1.27 introduces independently parameterized methods on non-interface receiver types. This differs from earlier generic receiver methods that only bind the type parameters of their receiver. The installed Go 1.23.2 compiler does not support the new syntax. Learn the equivalent standalone function first, then choose the newer method only with a verified Go 1.27+ environment.
package main
import ( "fmt")
type Box[T any] struct{ V T }
func MapBox[T, U any](b Box[T], f func(T) U) Box[U] { return Box[U]{V: f(b.V)} }func main() { b := Box[int]{V: 5} s := MapBox(b, func(n int) string { return fmt.Sprintf("n=%d", n) }) fmt.Println(s.V)}MapBox introduces independent input and output types. This standalone form works in Go 1.18+. A Go 1.27+ method could instead be declared func (b Box[T]) Map[U any](f func(T) U) Box[U] { return Box[U]{V: f(b.V)} }. This is a version-specific illustration, not a locally executed program. Official release notes: https://go.dev/doc/go1.27. Interface methods still cannot declare their own type parameters or be implemented by generic methods.
Expected output:
n=5Use a receiver method with the same type
package main
import ( "fmt")
type Box[T any] struct{ V T }
func (b Box[T]) Replace(v T) Box[T] { return Box[T]{V: v} }func main() { b := Box[int]{V: 2} c := b.Replace(9) fmt.Println(b.V, c.V)}Replace only uses the receiver’s existing T, so it works without independent method parameters. If an API needs another type parameter, a standalone generic function is a compatibility option. Do not increase the module language version without checking deployment tools and dependencies.
Expected output:
2 9Try it locally
Implement standalone Convert[T,U any](v T, f func(T) U) U. Convert 7 to the string "7" using fmt.Sprint in a callback.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 08: Plan generic methods for Go 1.27
Check the lesson objective before moving on.
Which release adds independently parameterized methods?
What is a compatible alternative on Go 1.23?