Go 1.18 adds generics to the language. In a nutshell, this allows writing code with types that can be specified later and instantiated when needed.
One last thing to note about type parameters is that they can’t be used with method arguments, only with function arguments:
or method receivers:
If we want to use generics with methods, it’s the receiver that needs to be a type parameter.
When are generics useful? Let’s discuss a few common uses where generics are recommended:
Data structures—We can use generics to factor out the element type if we implement a binary tree, a linked list, or a heap, for example.
Functions working with slices, maps, and channels of any type—A function to merge two channels would work with any channel type, for example. Hence, we could use type parameters to factor out the channel type:
Factoring out behaviors instead of types—The sort package, for example, contains a sort.Interface interface with three methods:
This interface is used by different functions such as sort.Ints or sort.Float64s. Using type parameters, we could factor out the sorting behavior (for example, by defining a struct holding a slice and a comparison function):
Then, because the SliceFn struct implements sort.Interface, we can sort the provided slice using the sort.Sort(sort.Interface) function:
In this example, factoring out a behavior allows us to avoid creating one function per type.
Conversely, when is it recommended that we not use generics?
When calling a method of the type argument—Consider a function that receives an io.Writer and calls the Write method, for example:
In this case, using generics won’t bring any value to our code whatsoever. We should make the w argument an io.Writer directly.
When it makes our code more complex—Generics are never mandatory, and as Go developers, we have lived without them for more than a decade. If we’re writing generic functions or structures and we figure out that it doesn’t make our code clearer, we should probably reconsider our decision for that particular use case.
Although generics can be helpful in particular conditions, we should be cautious about when to use them and when not to use them. In general, if we want to answer when not to use generics, we can find similarities with when not to use interfaces. Indeed, generics introduce a form of abstraction, and we have to remember that unnecessary abstractions introduce complexity.
Again, let’s not pollute our code with needless abstractions, and let’s focus on solving concrete problems for now. This means that we shouldn’t use type parameters prematurely. Let’s wait until we are about to write boilerplate code to consider using generics.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律