在golang中,如何在不同的包中对对象进行子类化?

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年9月2日 18:18:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/25621025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定