Generics has been included since version 1.18 of the Go language.
To the extent that I use the Go language, I thought I would never use Generics because I don't write generic functions and the function descriptions are long.
Useful features were added.
However, I was not at all familiar with Generics, so I decided to take a look at it just to get a feel for it, and found that modules related to slice
and map
were added to the Generics installation, although they were treated as experimental.
These are so-called convenience methods for arrays and maps that are common in other languages.
For example, you want to get an array sorted by map key, as in the JavaScript below.
JavaScript
const data = { "B": 2, "A": 1, "C": 3, } const keys = Object.keys(data).sort(); console.log(keys);
[ 'A', 'B', 'C' ]
This can be written in a new module of the Go language as follows
Go Language
package main import ( "fmt" "golang.org/x/exp/maps" "golang.org/x/exp/slices" ) func main() { data := map[string]int{ "B": 2, "A": 1, "C": 3, } keys := maps.Keys(data) slices.Sort(keys) fmt.Printf("%+v\n", keys) }
[A B C]
I wanted this feature!
Until now, when I tried to do the same thing without generics, I had to write it myself using a stupid for statement, but now I can write it as neatly as in other languages.
Since the array/map itself is rewritten, it cannot be written in a method chain like other languages, but I think this way of writing is suitable for the Go language, since there are cases where we do not want new arrays/maps to be generated for speed and efficiency.
If you don't want to rewrite yourself, there are functions available to generate a copy of the array/map, so you can just use that to rewrite the copy.
I knew Generics was a must.
In this way, even if I do not write generics myself, I am sure that the number of situations in which I will use generics will increase and it will become indispensable.
Since there are no filter
or forEach
type functions at this time, we hope that various functions will be implemented and promoted to the standard library in the future.
Also, although I often use Go language concurrency because it is useful, I would like to see a standard library for task pipelines using Generics (like RxGo converted to Generics) because I write the same kind of code from scratch every time using Goroutines and Channels.