区分同一包中具有相同名称的结构
Go Differentiate Between Structs with same name in the same package
背景:
我试图缓存一些结构信息以提高效率,但我无法区分同一包中具有相同名称的结构。
示例代码:
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)
}
问题
找不到合适的唯一键为:
- 名字相同"Test"
- PkgPath 相同,因为两个函数在同一个包中
- 指针等已出局,因为需要一个一致的密钥,否则缓存将毫无意义
任何人都可以帮助找到一种方法来唯一标识这些结构吗?
P.S。我确实意识到更改结构名称可以解决问题,但需要处理这种情况,因为我有一个其他人将调用的通用库,并且可能具有如上例定义的结构。
要唯一标识映射中的类型,请使用 reflect.Type
作为映射键:
var cache map[reflect.Type]cachedType
这是reflect documentation推荐的:
To test for [type] equality, compare the Types directly.
背景:
我试图缓存一些结构信息以提高效率,但我无法区分同一包中具有相同名称的结构。
示例代码:
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)
}
问题
找不到合适的唯一键为:
- 名字相同"Test"
- PkgPath 相同,因为两个函数在同一个包中
- 指针等已出局,因为需要一个一致的密钥,否则缓存将毫无意义
任何人都可以帮助找到一种方法来唯一标识这些结构吗?
P.S。我确实意识到更改结构名称可以解决问题,但需要处理这种情况,因为我有一个其他人将调用的通用库,并且可能具有如上例定义的结构。
要唯一标识映射中的类型,请使用 reflect.Type
作为映射键:
var cache map[reflect.Type]cachedType
这是reflect documentation推荐的:
To test for [type] equality, compare the Types directly.