Menu

Post image 1
Post image 2
1 / 2
0

"Generic Methods in Go 1.27"

Hacker News·"Generic Methods in Go 1.27"·27 days 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 . Even though other methods wouldn’t use U , they still had to keep it in their receiver declarations.…

Continue reading — create a free account

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

Read More