17 ms·
A generic abs? Not particularly useful, you're right. But he was using that as a trivial example. Generics are incredibly useful in a lot of contexts. One conte
by eridius 13y ago
A generic abs? Not particularly useful, you're right. But he was using that as a trivial example. Generics are incredibly useful in a lot of contexts. One context that the author touched on briefly is new container types. In Go, if I have a Slice, the type of element the slice contains is specified. But if I have a user-defined container, either the container has to be specialized for a single type (which makes it largely useless, at least as reusable code), or it has to take interface{}, which really sucks. No more homogenous container, no more static type information when working with this container, etc.
- burntsushi 13y agoTrivial examples are terrible as evidence to support a point. Trivial examples are generally good for pedagogical purposes, which doesn't really fit with the OP. 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 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.
- eridius 13y agoIt's more than just feeling pain when writing code. Using interface{} has a runtime cost. Both because of the vtable and because it requires heap-allocating something that could otherwise be inline.
- burntsushi 13y agoYes, that's true. The "pain" I had in mind wasn't in using `interface{}`, but in writing non-generic code. This doesn't result in a performance loss, but will result in some code duplication. (Or alternatively, extra complexity from using some sort of code generator.) But, to be fair, in the Go world, both mechanisms are used. It depends on which costs are important.