繁体   English   中英

通过Go中的界面修改结构成员

[英]Modifying struct members through an interface in Go

在我的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)
}

las,这行不通。 它可以编译,看起来可以正常运行,但是我没有得到想要的结果。 这是打印输出:

在Thing.DoStuff中,o = {{55 99}}
某物=&{{0 0}}

我显然希望最后一张印刷品说“某物=&{{55 99}}”

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM