【问题标题】:Modifying struct members through an interface in Go通过 Go 中的接口修改结构成员
【发布时间】:2012-07-13 20:04:21
【问题描述】:

在我的一个 Go 项目中,我想创建一个基类的多个子类,并能够通过基类/接口变量对子类的实例进行操作(I' m 使用“类”这个词,即使这个概念在 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}}
某事 = &{{0 0}}

我显然希望最后的打印结果是“Something = &{{55 99}}”

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

【问题讨论】:

    标签: inheritance interface struct go


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多