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

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

Subclassing an object in a different package in golang

问题

我正在尝试为我的所有结构体创建一个基础对象,但是当我创建的新对象位于不同的包中时,无法使其正常工作。当它们位于同一个包/文件夹中时,它可以正常工作。

例如,为所有对象创建一个基类:

  1. package Test
  2. type BaseObject struct {
  3. base interface{}
  4. }

---- 子文件夹 Test\Stuff ---

创建一个继承 BaseObject 的新 TestObject:

  1. package Stuff
  2. import Test "Test"
  3. type TestObject struct{
  4. Test.BaseObject
  5. }
  6. func (this *TestObject)DoSomething(){
  7. this.base this.BaseObject.base 的任何引用都会失败!!!
  8. }

--- 在同一个文件夹中,一切正常 ---

  1. package Test
  2. type TestObject struct{
  3. BaseObject
  4. }
  5. func (this *TestObject)DoSomething(){
  6. this.base 的任何引用都可以正常工作??
  7. }
英文:

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

  1. package Test
  2. type BaseObject struct {
  3. base interface{}
  4. }

---- Sub Folder Test\Stuff ---

create a new TestObject which subclasses BaseObject

  1. package Stuff
  2. import Test "Test"
  3. type TestObject struct{
  4. Test.BaseObject
  5. }
  6. func (this *TestObject)DoSomething(){
  7. any reference to this.base or this.BaseObject.base fails!!!
  8. }

--- In the same folder, everthing works ---

  1. package Test
  2. type TestObject struct{
  3. BaseObject
  4. }
  5. func (this *TestObject)DoSomething(){
  6. any reference to this.base works fine??
  7. }

答案1

得分: 6

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

如果你只是这样做:

  1. type BaseObject struct {
  2. Base interface{}
  3. }

Base 将在其他包的上下文中被公开或“公共”,一切都会正常工作。

英文:

You can't reference hidden or "private" fields in structs outside their packages.

If you would just do:

  1. type BaseObject struct {
  2. Base interface{}
  3. }

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:

确定