为什么他们不使用int来定义常量而不是使用位移运算符?

caf*_*00d 0 go

在go源代码中,常量bucketCnt是8.为什么用右移3次定义而不是仅仅定义为8.我理解这1 << x意味着2^x.

但是,我的问题是......

是

// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt     = 1 << bucketCntBits
Run Code Online (Sandbox Code Playgroud)

比...更好

// Maximum number of key/value pairs a bucket can hold.
bucketCnt     = 8
Run Code Online (Sandbox Code Playgroud)

pet*_*rSO 5

const (
  // Maximum number of key/value pairs a bucket can hold.
  bucketCntBits = 3
  bucketCnt     = 1 << bucketCntBits
)
Run Code Online (Sandbox Code Playgroud)

存储桶可以容纳的键/值对的数量取决于使用的位数(bucketCntBits = 3).这转换为桶数(bucketCnt)1 << bucketCntBits或8.如果我们将位数更改为4(bucketCntBits = 4)或2(bucketCntBits= 2),则bucketCnt仍然是1 << bucketCntBits16或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.
Run Code Online (Sandbox Code Playgroud)

"散列的低位用于选择存储桶."

参考文献:

SRC /运行/ hashmap.go

去地图实际行动

GopherCon 2016:Keith Randall - 在地图实施中

Go的地图内部宏观视图(2013)