在golang中对不同包中的对象进行子类化

时间:2014-09-02 10:18:03

标签: go subclassing

我试图为golang中的所有结构创建一个基础对象。出于某种原因,当我创建的新对象位于不同的包中时,我无法使其工作。它们在同一个包/文件夹中时工作正常。

e.g。所有对象的基类

package Test

type BaseObject struct {
    base interface{}
}

----子文件夹测试\东西---

创建一个新的TestObject,它是BaseObject的子类

package Stuff

import Test "Test"

type TestObject struct{
    Test.BaseObject
}
func (this *TestObject)DoSomething(){
    any reference to this.base or this.BaseObject.base fails!!!
}

---在同一文件夹中,外翻工作---

package Test

type TestObject struct{
    BaseObject
}
func (this *TestObject)DoSomething(){
    any reference to this.base works fine??
}

1 个答案:

答案 0 :(得分:6)

您不能在其包外的结构中引用隐藏或“私有”字段。

如果您愿意:

type BaseObject struct {
    Base interface{}
}

Base将在其他包的上下文中公开或“公开”,一切都会有效。