The Go team released Go 1.18 Beta 1 on December 14th, officially introducing support for generics. See The Go Blog for more details. I recently downloaded and tried it out.
Download and Installation
Follow the official documentation to download and install the beta version:
❯ go install golang.org/dl/go1.18beta1@latest
# Note: The executable files below are located in $GOPATH/bin. If the environment variables are not configured, you can manually specify the path.
❯ go1.18beta1 download
❯ go1.18beta1 version
go version go1.18beta1 linux/amd64
Installation is complete!
Simple Experience
Referring to the official generics documentation, we can easily write a method that sums any slice of addable elements:
Since Go's toolchain has not been updated to support the new syntax, vscode will show syntax errors. However, the actual output of the program matches the expected result.
In-Depth Understanding
Many people may want to further understand the syntax and usage of Go's new generics. Unfortunately, it seems that the official documentation only provides the simple document mentioned earlier and does not provide a more detailed explanation. Currently, I have only found some third-party generic examples. If you are interested, you can read the code to deepen your understanding.
Personal Thoughts
Perhaps due to the lack of documentation, just looking at the examples makes it difficult for me to imagine the practical use of generics. Initially, what I wanted to try with generics was to implement sorting for slices of multiple types, that is, to implement sort.Interface
in bulk:
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with index i
// must sort before the element with index j.
//
// If both Less(i, j) and Less(j, i) are false,
// then the elements at index i and j are considered equal.
// Sort may place equal elements in any order in the final result,
// while Stable preserves the original input order of equal elements.
//
// Less must describe a transitive ordering:
// - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
// - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
//
// Note that floating-point comparison (the < operator on float32 or float64 values)
// is not a transitive ordering when not-a-number (NaN) values are involved.
// See Float64Slice.Less for a correct implementation for floating-point values.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
After spending a long time writing it, I couldn't make it work, so I gave up... If any readers have knowledge about it, I hope you can enlighten me in the comments.
I hope to see detailed generics documentation from the Go team soon!