Modifying struct members through an interface in Go

Mic*_*ael 0 inheritance struct interface 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).

Here's what it might look like in C++ just to show what I mean:

#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;
}
Run Code Online (Sandbox Code Playgroud)

This would print "gSomething = {55, 99}". Being new to Go I was hoping I could do something like this (which I felt was fairly clean):

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)
}
Run Code Online (Sandbox Code Playgroud)

Alas, this doesn't work. 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}}
Something = &{{0 0}}

I was obviously hoping for the last print to say "Something = &{{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?

tux*_*21b 5

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