英文:
Thrift go support of map with struct value as key
问题
我使用Thrift 0.9.1进行了Golang生成的实验,例如:
Thrift定义如下:
struct AppIdLeveledHashKeyTimeKeyHour {
1: required i32 appId
2: required LeveledHashKey leveledHashKey
3: required TimeKeyHour timeKeyHour
}
typedef map<AppIdLeveledHashKeyTimeKeyHour, ...sth else...> EventSliceShardIdValue
在生成的代码中,EventSliceShardIdValue会变成:
type EventSliceShardIdValue map[*AppIdLeveledHashKeyTimeKeyHour]EventSliceAppIdLeveledHashKeyTimeKeyHourValue
你可以看到,关键部分是一个指针,表示内存地址。在Golang中,大多数情况下,将指针作为map的键(而不是值或对象的哈希值)是没有意义的。要将一些字段的组合作为map的键,定义应该使用值类型,如:
map[AppIdLeveledHashKeyTimeKeyHour]EventSliceAppIdLeveledHashKeyTimeKeyHourValue
这是Thrift的Golang支持的问题(或者我误用了某些东西)吗?有没有解决这个问题的方法?
英文:
I experimented golang generation with Thrift 0.9.1, for example,
thrift definition,
struct AppIdLeveledHashKeyTimeKeyHour {
1: required i32 appId
2: required LeveledHashKey leveledHashKey
3: required TimeKeyHour timeKeyHour
}
typedef map<AppIdLeveledHashKeyTimeKeyHour, ...sth else...> EventSliceShardIdValue
in the generated code, EventSliceShardIdValue would be,
type EventSliceShardIdValue map[*AppIdLeveledHashKeyTimeKeyHour]EventSliceAppIdLeveledHashKeyTimeKeyHourValue
you can find the key part is a pointer which represents memory address. In golang a pointer as map key (instead of a value, or hash of the obj) is useless in most cases. To use a combination of some fields as map key, the definition should use a value type like
map[AppIdLeveledHashKeyTimeKeyHour]EventSliceAppIdLeveledHashKeyTimeKeyHourValue
Is it a problem of Thrift's go support (or I misused sth)? Any workaround to solve this problem in thrift?
答案1
得分: 0
结构体(不包含指针)只能在某些有限的情况下用作映射键(根据http://golang.org/ref/spec#Comparison_operators,它们必须是可比较的);可能AppIdLeveledHashKeyTimeKeyHour
不符合这个定义,所以实际上无法在不使用指针作为键的情况下构建映射。
英文:
Structs (without pointers) can only be used as map keys under certain limited circumstances (they must be comparable per http://golang.org/ref/spec#Comparison_operators); it's possible that AppIdLeveledHashKeyTimeKeyHour
doesn't fit this definition, so it's not actually possible to build a map without using a pointer for the key.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论