Go Differentiate Between Structs with same name in the same package

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

Go Differentiate Between Structs with same name in the same package

问题

背景:

我正在尝试为了提高效率而缓存一些结构体信息,但在同一个包中的同名结构体之间区分起来有些困难。

示例代码:

func Struct(s interface{}) {
  val := reflect.ValueOf(s)
  typ := val.Type()

  // 在映射中缓存,但用什么键?
  typ.Name()               // 不够好
  typ.PkgPath + typ.Name() // 不够好
}

func Caller1() {
  type Test struct {
    Name string
  }

  t := Test{
    Name: "Test Name",
  }

  Struct(t)
}

func Caller2() {
  type Test struct {
    Address string
    Other   string
  }

  t := Test{
    Address: "Test Address",
    Other:   "OTHER",
  }

  Struct(t)
}

问题

无法找到一个适当的唯一键,因为:

  • 名称相同为"Test"
  • PkgPath相同,因为两个函数都在同一个包中
  • 指针等不行,因为需要一个一致的键,否则缓存就没有意义

有人能帮忙找到一种唯一标识这些结构体的方法吗?

P.S. 我意识到更改结构体名称可以解决这个问题,但需要处理这种情况,因为我有一个通用库,其他人会调用它,并且可能会像上面的示例中定义结构体。

英文:

Background:

I am trying to cache some struct information for efficiency but am having trouble differentiating between struct with the same name, within the same package.

Example Code:

func Struct(s interface{}){
  val := reflect.ValueOf(s)
  typ := val.Type()

  // cache in map, but with what key? 
  typ.Name()               // not good enough
  typ.PkgPath + typ.Name() // not good enough
}

func Caller1() {
  type Test struct {
    Name string
  }

  t:= Test{
    Name:"Test Name",
  }

  Struct(t)
}

func Caller2() {
  type Test struct {
    Address string
    Other string
  }

  t:= Test{
    Address:"Test Address",
    Other:"OTHER",
  }

  Struct(t)
}

Problem

Can't find a proper unique key as:

  • Name is the same "Test"
  • PkgPath with be identical as both functions are in same package
  • Pointers etc is out because need a consistent key otherwise caching would be pointless

Can anyone help in finding a way to uniquely identify these structs?

P.S. I do realize that changing of the struct name would solve the issue, but need to handle this scenario as I have a generic library that others will be calling and may have the structs defined like the above example.

答案1

得分: 2

要在映射中唯一标识类型,请使用reflect.Type作为映射的键:

var cache map[reflect.Type]cachedType

这是由reflect文档推荐的方法:

> 要测试类型的相等性,请直接比较类型。

英文:

To uniquely identify types in a map, use reflect.Type as the map key:

var cache map[reflect.Type]cachedType

This is recommended by the reflect documentation:

> To test for [type] equality, compare the Types directly.

huangapple
  • 本文由 发表于 2015年11月28日 02:29:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/33963048.html
匿名

发表评论

匿名网友

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

确定