I've come to a point in a Go project of mine where I'd like to create multiple subclasses of a base class, and be able to operate on instances of the subclasses through a base class/interface variable (I'm using the word "class" even though the concept doesn't really exist in Go).
Here's what it might look like in C++ just to show what I mean:
#include <iostream>
using namespace std;
class Base {
public:
int x,y;
virtual void DoStuff() {};
};
class Thing : public Base {
public:
void DoStuff() { x = 55; y = 99; }
};
Base *gSomething;
int main(int argc, char **argv) {
gSomething = new Thing();
gSomething->DoStuff();
cout << "gSomething = {" << gSomething->x << ", " << gSomething->y << "}" << endl;
return 0;
}
This would print "gSomething = {55, 99}". Being new to Go I was hoping I could do something like this (which I felt was fairly clean):
package main
import "fmt"
type IBase interface {
DoStuff()
}
// The base "class"
type Base struct {
x, y int
}
// A more specific variant of Base
type Thing struct {
Base
}
func (o Base) DoStuff() {
// Stub to satisfy IBase
}
func (o Thing) DoStuff() {
o.x, o.y = 55, 99
fmt.Println("In Thing.DoStuff, o = ", o)
}
var Something IBase
func main() {
Something = new (Thing)
Something.DoStuff()
fmt.Println("Something = ", Something)
}
Alas, this doesn't work. It compiles, it appears to run properly, but I don't get the result I wanted. Here's the printout:
In Thing.DoStuff, o = {{55 99}}
Something = &{{0 0}}
I was obviously hoping for the last print to say "Something = &{{55 99}}"
Am I completely off on the design here (is this not possible to do in Go), or have I just missed some small detail?