给指针类型的结构属性添加方法

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

Add method to Struct Property of pointer type

问题

我有这个结构体:

type AppContext struct {
	DB                *db.DB
	Properties        *db.Col
}

Properties 是类型为 *db.ColTiedot 集合。

我的问题是,对于我的缓冲系统,我想能够获取集合的名称。奇怪的是,该库的默认部署无法做到这一点。

当我这样实例化 AppContext

App = AppContext{}

然后执行:

App.DB.Create("Properties")
App.Properties = App.DB.Use("Properties")

我想添加一个实例方法,但它不允许我这样做:

func (dbCol App.Properties) ColName() string {
	return "Properties"
}

你有什么办法可以实现这个,或者以更智能的方式扩展 Tiedot 吗?

英文:

I have this struct:

type AppContext struct {
	DB                *db.DB
	Properties        *db.Col
}

Properties of the Type *db.Col is a Tiedot Collection.

The problem I have is that for my buffering system I want to be able to fetch name of the collection. Weirdly enough the default deployment of the library can't do it.

When I instantiate the AppContext like so:

App = AppContext{}

..and then do:

App.DB.Create("Properties")
App.Properties = App.DB.Use("Properties")

I want to add an instance method, but it doesn't allow me to:

func (dbCol App.Properties) ColName() string {
	return "Properties"
}

Any idea how I could accomplish this or maybe extend Tiedot in a smarter way?

答案1

得分: 1

我不认为在Go语言中可以实现这样的扩展。然而,我确信问题可以用其他方式解决。例如,你可以创建一个包含集合和其名称的结构体:

type Collection struct {
  Col *tiedot.Col
  Name string
}

然后进行初始化:

App.Properties = Collection{App.DB.Use("Properties"), "Properties"}
英文:

I do not think that such extension is possible in Go. However, I sure that the problem can be solved in some other way. For example, you can create structure that holds the collection and its name:

type Collection struct {
  Col *tiedot.Col
  Name string
}

and initialise it

App.Properties = Collection{App.DB.Use("Properties"), "Properties"}

huangapple
  • 本文由 发表于 2015年8月3日 00:42:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/31774131.html
匿名

发表评论

匿名网友

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

确定