Menu

1 / 2

"Generic Methods in Go 1.27"

Hacker News·3 months ago
#G5g5nlKg
Reading 0:00
15s threshold

When Go 1.18 introduced Generics in 2022, it brought generic type parameters to functions and structs, but left out methods. With the release of Go 1.27, this long-standing limitation has been removed. Methods can now define their own type parameters without adding them to the receiving struct.

Why this change was introduced

If you want to create a graph node that holds a generic value, you might implement it like this:

type Node [ T any ] struct { value T }

Imagine adding a method Map that transforms a node of type T into a node of another type U . Prior to Go 1.27, you were forced to add U directly to the Node struct itself:

type Node [ T any , U any ] struct { value T } func ( n * Node [ T , U ]) Map () Node [ T , U ] { // ... }

Adding U to the struct itself is bad design because U is a type parameter specific to Map .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.