[英]Modifying struct members through an interface in Go
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). 在我的Go项目中,我想创建一个基类的多个子类,并能够通过基类/接口变量对这些子类的实例进行操作(我正在使用即使该概念在Go中实际上并不存在)。
Here's what it might look like in C++ just to show what I mean: 这是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;
}
This would print "gSomething = {55, 99}". 这将显示“ gSomething = {55,99}”。 Being new to Go I was hoping I could do something like this (which I felt was fairly clean): 刚开始使用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)
}
Alas, this doesn't work. las,这行不通。 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}} 在Thing.DoStuff中,o = {{55 99}}
Something = &{{0 0}} 某物=&{{0 0}}
I was obviously hoping for the last print to say "Something = &{{55 99}}" 我显然希望最后一张印刷品说“某物=&{{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? 我是否完全放弃了这里的设计(在Go中是不可能做到的),还是只是错过了一些小细节?
Your func (o Thing) DoStuff()
has a receiver of the type Thing struct
and structs are passed by value in Go. 您的func (o Thing) DoStuff()
具有类型为Thing struct
的接收器,并且在Go中按值传递结构。 If you want to modify the struct (and not a copy of it), you would have to pass it by reference. 如果要修改该结构(而不是其副本),则必须通过引用传递它。 Change this line to func (o *Thing) DoStuff()
and you should see the expected output. 将此行更改为func (o *Thing) DoStuff()
,您应该会看到预期的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.