 2017-03-12 03:17

# 他们为什么不使用整数来定义常量而不是使用移位运算符？

In the go source code, the constant `bucketCnt` is 8. Why is defined in terms of right-shifting 3 times instead of just defining it as 8. I understand that `1 << x` implies `2^x`.

But, my question is...

Is

``````// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt     = 1 << bucketCntBits
``````

better than

``````// Maximum number of key/value pairs a bucket can hold.
bucketCnt     = 8
``````
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• duanfu5239 2017-03-12 03:38
已采纳
``````const (
// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt     = 1 << bucketCntBits
)
``````

The number of key/value pairs a bucket can hold depends on the number of bits used (`bucketCntBits = 3`). That translates to a bucket count (`bucketCnt`) of `1 << bucketCntBits` or 8. If we change the number of bits to 4 (`bucketCntBits = 4`) or 2 (`bucketCntBits` = 2) then `bucketCnt` is still `1 << bucketCntBits` or 16 or 4.

``````// A map is just a hash table. The data is arranged
// into an array of buckets. Each bucket contains up to
// 8 key/value pairs. The low-order bits of the hash are
// used to select a bucket. Each bucket contains a few
// high-order bits of each hash to distinguish the entries
// within a single bucket.
``````

"The low-order bits of the hash are used to select a bucket."

References:

src/runtime/hashmap.go

Go maps in action

GopherCon 2016: Keith Randall - Inside the Map Implementation

Macro View of Map Internals In Go (2013)

已采纳该答案
打赏 评论
• douchenbiao0916 2017-03-12 03:43

Using bit shift operators sets `bucketCnt` to be defined according to the value in `bucketCntBits`, so if `bucketCntBits` is changed, `bucketCnt` will change accordingly. Also, it more clearly expresses how `bucketCntBits` is related to `bucketCnt`.

打赏 评论