背景:
我正在尝试缓存某些结构信息以提高效率,但是在区分同一包内具有相同名称的结构时遇到了麻烦。
示例代码:
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)
}
问题
找不到适当的唯一键,例如:
任何人都可以帮助找到一种唯一识别这些结构的方法吗?
附言我确实意识到更改结构名称可以解决此问题,但是需要处理这种情况,因为我有一个通用库,其他人会在此库中调用,并且可能已定义了与上述示例类似的结构。
最佳答案
要唯一标识 map 中的类型,请使用 reflect.Type
作为 map 键:
var cache map[reflect.Type]cachedType
这是reflect documentation推荐的:
关于reflection - 在同一个程序包中使用相同名称区分结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33963048/