dsh1956 2012-07-13 20:04
浏览 17
已采纳

通过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;
}

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

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?

  • 写回答

1条回答 默认 最新

  • douruoshen1449 2012-07-13 20:39
    关注

    Your func (o Thing) DoStuff() has a receiver of the type Thing struct and structs are passed by value in 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题