私のGoプロジェクトで、基本クラスの複数のサブクラスを作成し、基本クラス/インターフェイス変数を介してサブクラスのインスタンスを操作できるようにしたいところに到達しました(私は概念は実際にはGoには存在しませんが、「クラス」という単語)。
私が何を意味するかを示すために、C++でどのように見えるかを次に示します。
#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;
}
これにより、「gSomething ={55,99}」が出力されます。Goに慣れていないので、次のようなことができると思っていました(かなりきれいだと感じました)。
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)
}
残念ながら、これは機能しません。コンパイルされ、正しく実行されているように見えますが、希望する結果が得られません。印刷物は次のとおりです。
Thing.DoStuffでは、o = {{55 99}}
Something =&{{0 0}}
私は明らかに最後の印刷物が「何か=&{{5599}}」と言うことを望んでいました
私はここでデザインを完全にオフにしていますか(これはGoでは不可能ですか)、それとも細部を見逃しただけですか?