英文:
Subclassing an object in a different package in golang
问题
我正在尝试为我的所有结构体创建一个基础对象,但是当我创建的新对象位于不同的包中时,无法使其正常工作。当它们位于同一个包/文件夹中时,它可以正常工作。
例如,为所有对象创建一个基类:
package Test
type BaseObject struct {
base interface{}
}
---- 子文件夹 Test\Stuff ---
创建一个继承 BaseObject 的新 TestObject:
package Stuff
import Test "Test"
type TestObject struct{
Test.BaseObject
}
func (this *TestObject)DoSomething(){
对 this.base 或 this.BaseObject.base 的任何引用都会失败!!!
}
--- 在同一个文件夹中,一切正常 ---
package Test
type TestObject struct{
BaseObject
}
func (this *TestObject)DoSomething(){
对 this.base 的任何引用都可以正常工作??
}
英文:
I'm trying to create a base object for all my structs in golang. For some reason I can't get it to work when the new object I create is in a different package. It works fine when they are in the same package/folder.
e.g. a base class for all objects
package Test
type BaseObject struct {
base interface{}
}
---- Sub Folder Test\Stuff ---
create a new TestObject which subclasses 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!!!
}
--- In the same folder, everthing works ---
package Test
type TestObject struct{
BaseObject
}
func (this *TestObject)DoSomething(){
any reference to this.base works fine??
}
答案1
得分: 6
你不能在结构体外部的包中引用隐藏或“私有”字段。
如果你只是这样做:
type BaseObject struct {
Base interface{}
}
Base
将在其他包的上下文中被公开或“公共”,一切都会正常工作。
英文:
You can't reference hidden or "private" fields in structs outside their packages.
If you would just do:
type BaseObject struct {
Base interface{}
}
Base
will be exposed or "public" in the context of other packages, and everything will work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论