Inheritance 通过Go中的接口修改结构成员

Inheritance 通过Go中的接口修改结构成员,inheritance,interface,struct,go,Inheritance,Interface,Struct,Go,在我的一个Go项目中,我想创建一个基类的多个子类,并能够通过基类/接口变量对这些子类的实例进行操作(我使用“class”一词,即使这个概念在Go中并不存在) 这就是C++中可能显示的意思: #include <iostream> using namespace std; class Base { public: int x,y; virtual void DoStuff() {}; }; class Thing : public Base { public:

在我的一个Go项目中,我想创建一个基类的多个子类,并能够通过基类/接口变量对这些子类的实例进行操作(我使用“class”一词,即使这个概念在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;
}
唉,这行不通。它可以编译,看起来运行正常,但是我没有得到我想要的结果。这是打印件:

在Thing.DoStuff中,o={{5599}
Something=&{0}

很明显,我希望最后一篇文章会说“Something=&{{5599}”

我是否完全偏离了这里的设计(这在Go中是不可能做到的),或者我只是错过了一些小细节?

您的
func(o Thing)DoStuff()
有一个类型为
Thing struct
的接收器,并且结构在Go中按值传递。如果要修改结构(而不是它的副本),则必须通过引用传递它。将此行更改为
func(o*Thing)DoStuff()
,您将看到预期的输出

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)
}