by personZ · 12y ago · 0 comments
This particular piece (by a high school student, as an aside) starts off trying to create a surrogate for generics in Go.
Don't.
Here's the thing -- most of these posts are not about people making real code, but people making -toy- code. Where every function is all things to all people.
The number of times I've needed a generic abs in my life -- zero.
The number of times I've needed a double floating point abs in my life -- every single time.
That's the thing about generics and real, actual world code: Your types are generally much less amorphous than you think. They really are. This illusion that everything needs to be everything just does not hold in the real world.
But it is always the tiring example used against Go. Boring.
For example, the OP mentioned that using a stack in Go requires casting from `interface{}`. But this is patently ridiculous. Most people who need a stack in Go just use a slice: https://code.google.com/p/go-wiki/wiki/SliceTricks --- Is this a bit messier and limited than a container type suited to stacks? Yes! But it gets the job done the majority of the time. Therefore, it's not as big of a problem as the article leads you to believe.
Not all things require clean polymorphic container types. Sometimes you can get by with less. And when you need more, you're going to feel a bit of pain with a less expressive type system. It's all part of the trade off. But it's not good to represent this as a scenario where it's all just bad stuff all the time.
But, to be fair, in the Go world, both mechanisms are used. It depends on which costs are important.
The number of times you'll need a generic map or fold algorithm to operate on those structures: many, many times.
https://github.com/petar/gollrb
So if you need a data structure like this, you can do it without much trouble without generics. Perhaps you don't feel that solution is as clean, but it's certainly pretty easy to do.
NB that golang has not ruled out generics, it's just not something they felt compelled to put in initially, and not many people who use the language miss them.
What about a generic max() or min() function?
x = append(x, a, b, c)
[0] http://golang.org/pkg/container/list/The abs example could be reduced to:
import "github.com/joeshaw/gengen/generic"
func abs(x generic.T) generic.T {
if x < 0 {
return -x
}
return x
}
You could then generate different type-specific versions: gengen abs.go int32 | gofmt -r 'abs -> absInt32' > abs_int32.go
gengen abs.go float64 | gofmt -r 'abs -> absFloat64' > abs_float64.go
...
The downside is that the API is annoyingly non-generic (a different abs variant for each type) but at least you didn't have to type it in a bunch of times.I agree that abs() is kind of a toy example, but this approach has helped me a lot for various slice operations like indexing and deleting.