Go language, structs and inheritance

Dec 24, 2011 17:24

I wish the go language had subclassing or macros or templates or something. These are all ways of reusing code without copy and paste. A macro or a template can be applied by the compiler to apply the same code pattern to different data. Subclassing can make things applied to the old data also apply to a new expanded version of that data.
Right now this lack is making me kinda hate writing a container/collection class in go. If I write a LRUCache class, but then want to extend it to be an LRU cache which also expires cached elements by HTTP rules (a normal pattern of thinking for class design in Java or C++) in go I'm going to wind up copy and pasting the entire implementation in order to make an extended version of it.
In Java (or very nearly C++) I'd write:

class LRUCacheEntry {
Object it;
int foo, bar; // some metadata to track
}
then

class LRUHttpCacheEntry extends LRUCacheEntry {
long age; // more metadata to track
}
The subclass gets all of the members and functions of the superclass, and a little bit more. Go is missing this kind of composition or extension.
If the LRU cache behavior was written as a template or a macro, it might be applied to anything that had the right set of fields.
Instead, Go is advocating that classes implement interfaces of accessors. I'm annoyed at having to write lots of accessors, and I'm annoyed because I wanted to come to Go to write efficient and fast code which would compile and compete with the runtime speed of C or Java. Sure, requiring a virtualized function call to access a variable isn't the slowest thing ever, but do a few billion of them and I'll still be annoyed that other languages have good ways around requiring that.

hacking

Previous post Next post
Up