banner
amtoaer

晓风残月

叹息似的渺茫,你仍要保存着那真!
github
telegram
email
x
bilibili
steam

Go Generic Exploration

The Go team released Go 1.18 Beta 1 on December 14, officially introducing support for generics. For more information, see The Go Blog. I recently downloaded and tried it out.

Download and Installation#

Download and install the beta version according to the official documentation:

Installation is complete!

Simple Experience#

Referring to the official generics documentation, we can easily write a method that sums any addable slice:

image-20211224190117034

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 probably want to further understand the syntax and usage of Go's new generics. Unfortunately, it seems that the official documentation only provides the simple documentation 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. What I wanted to try most after getting generics was to implement sorting for slices of multiple types, that is, implementing sort.Interface in bulk:

After writing for a long time, I still couldn't succeed, so I gave up... If any readers have knowledge about this, I hope you can share your insights in the comments.

I hope to see detailed official documentation on generics in Go as soon as possible!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.