使用数字文字但不是数字常量的移位运算符错误

Adi*_*ngh 6 constants literals go

我在 go 中执行 shift 操作时invalid operation: 1 << bucketCntBits (shift count type int, must be unsigned integer)出错,尝试在 go inside main()body 中声明文字时出错失败文字示例:https : //play.golang.org/p/EqI-yag5yPp

func main() {
    bucketCntBits := 3 // <---- This doesn't work
    bucketCnt     := 1 << bucketCntBits
    fmt.Println("Hello, playground", bucketCnt)
}
Run Code Online (Sandbox Code Playgroud)

当我将班次计数声明为常数时,班次运算符就起作用了。工作常数示例:https : //play.golang.org/p/XRLL4FR8ZEl

const (
    bucketCntBits = 3 // <---- This works
)

func main() {

    bucketCnt     := 1 << bucketCntBits
    fmt.Println("Hello, playground", bucketCnt)
}
Run Code Online (Sandbox Code Playgroud)

为什么常量有效而文字不适用于移位运算符?

pet*_*rSO 5

Go 1.13 发行说明(2019 年 9 月)

语言的变化

根据有符号的移位计数提案, Go 1.13 删除了移位计数必须是无符号的限制。此更改消除了对许多人为 uint 转换的需要,引入只是为了满足 << 和 >> 运算符的此(现已删除)限制。


invalid operation: 1 << bucketCntBits (shift count type int, must be unsigned integer)
Run Code Online (Sandbox Code Playgroud)

这不再是 Go 1.13(2019 年 9 月)及更高版本的错误。

你的例子,

package main

import "fmt"

func main() {
    bucketCntBits := 3
    bucketCnt := 1 << bucketCntBits
    fmt.Println(bucketCnt)
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ go version
go version devel +66ff373911 Sat Aug 24 01:11:56 2019 +0000 linux/amd64

$ go run shift.go
8
Run Code Online (Sandbox Code Playgroud)