【问题标题】:Static member of a struct in GolangGolang中结构的静态成员
【发布时间】:2018-12-01 20:46:05
【问题描述】:

假设我有一个结构:

type DriverData struct {
    TypePath string = "Foo.Bar.DriverData"
}

我希望能够引用 TypePath 而不必创建结构的实例,例如:

typePath := DriverData.TypePath

但这在 Golang 中是不可能的。

所以我想知道 - 也许有一种方法可以创建地图,并将类型与字符串相关联,例如:

type DriverData struct {

}

type PilotData struct {

}

type BoatmasterData struct {

}

typeMap := map[struct]string{
   DriverData: "Foo.Bar.DriverData",
   PilotData:   "Foo.Bar.PilotData",
   BoatmasterData: "Foo.Bar.BoatmasterData",
}

问题:

这是在结构上创建静态属性的最佳方法吗?像这样在地图中存储静态属性?

【问题讨论】:

  • 你真正想做什么?
  • 我想将一个字符串存储在一个结构体、静态成员上,并对其进行硬编码。因此该结构用字符串标记。有道理吗?元编程的东西在这里。
  • 最终目标是让我可以在一个结构体上有一个字符串,它表示代码库中结构体的路径。
  • 听起来您正在尝试使用Golang 进行动态类型编程。我怀疑这是为此而生的,但反思可能会有所帮助。不太确定你想要达到什么目标。
  • 啊,所以类似于 Java 中的静态。好吧,我从来没有在我的 go 代码中做过这样的事情,只在 init 上初始化了带有值的单例结构,主要来自 JSON 字符串:( 我确实希望有这样的东西,所以我不必这样做。会在整个代码库的基本配置中提供很多帮助。

标签: go


【解决方案1】:

您可以定义方法来为您提供这些值:

type DriverData struct {
}

func (DriverData) Path() string {
    return "Foo.Bar.DriverData"
}

type PilotData struct {
}

func (PilotData) Path() string {
    return "Foo.Bar.PilotData"
}

type BoatmasterData struct {
}

func (BoatmasterData) Path() string {
    return "Foo.Bar.BoatmasterData"
}

这样做是你想要的吗?

https://play.golang.org/p/zR7RZwMVEdf

【讨论】:

  • 它不是静态成员。无论如何你声明了对象
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多