Reflection 在同一个包中区分具有相同名称的结构
背景:Reflection 在同一个包中区分具有相同名称的结构,reflection,go,identifier,Reflection,Go,Identifier,背景: 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
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)
}
我试图缓存一些结构信息以提高效率,但在区分同一个包中具有相同名称的结构时遇到困难
示例代码:
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)
}
问题
找不到正确的唯一密钥,因为:
- 名称与“测试”相同
- 具有的PkgPath必须相同,因为这两个函数位于同一个包中
- 指针etc不可用,因为需要一致的密钥,否则缓存将毫无意义
另外,我确实意识到更改结构名称可以解决此问题,但需要处理此情况,因为我有一个其他人将调用的通用库,并且可能会像上面的示例一样定义结构。要唯一标识映射中的类型,请使用映射键:
var cache map[reflect.Type]cachedType
这是由以下机构建议的:
要测试[type]是否相等,请直接比较这些类型
使用
reflect。键入作为地图键。非常感谢!我在我的代码的其他地方用过,我想我只是需要一双新的眼睛;因为天气原因,我看不见森林trees@joeybloggs:记住,你的问题得到了回答。