Thrift支持将结构体值作为键的映射。

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

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&lt;AppIdLeveledHashKeyTimeKeyHour, ...sth else...&gt; 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.

huangapple
  • 本文由 发表于 2014年4月20日 17:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/23180665.html
匿名

发表评论

匿名网友

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

确定