Go generics are not bad – Daniel Lemire's blog
Go generics are not bad
When programming, we often need to write ‘generic’ functions where the exact data type is not important. For example, you might want to write a simple function that sums up numbers.
Go lacked this notion until recently, but it was recently added (as of version 1.18). So I took it out for a spin.
In Java, generics work well enough as long as you need “generic” containers (arrays, maps), and as long as stick with functional idioms. But Java will not let me code the way I would prefer. Here is how I would write a function that sums up numbers:
int sum(int[] v) {
int summer = 0;
for(int k = 0; k < v.length; k++) {
summer += v[k];
}
return summer;
}
What if I need to support various number types? Then I would like to write the following generic function, but Java won’t let me.
// this Java code won't compile
static <T extends Number> T sum(T[] v) {
T summer = 0;
for(int k = 0; k < v.length; k++) {
summer += v[k];
}
return summer;
}
Go is not object oriented per se, so you do not have a ‘Number’ class. However, you can create your own generic ‘interfaces’ which serves the same function. So here is how you solve the same problem in Go:
type Number interface {
uint | int | float32 | float64
}
func sum[T Number](a []T) T{
var summer T
for _, v := range(a) {
summer += v
}
return summer
}
So, at least in this one instance, Go generics are more expressive than Java generics. What about performance?
If I apply the above code to an array of integers, I get the following tight loop in assembly:
pc11:
MOVQ (AX)(DX*8), SI
INCQ DX
ADDQ SI, CX
CMPQ BX, DX
JGT pc11
As far as Go is concerned, this is as efficient as it gets.
So far, I am giving an A to Go generics.
'Programming' 카테고리의 다른 글
[Oracle] DBMS_OUTPUT.PUT_LINE 출력창 보기 - SQL DEVELOPER (0) | 2022.07.20 |
---|---|
How to Use Parameters in PowerShell Part I - Simple Talk (red-gate.com) (0) | 2022.07.11 |
The history of C# (0) | 2022.06.28 |
No module named 'pip' 에러와 함께 pip가 갑자기 안되는 경우 · Tonic (jwgo.kr) (0) | 2022.05.08 |
업비트 마켓 메이킹 파이썬 봇 (0) | 2022.05.05 |