我在 go with 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)
}
当我将移位计数声明为常量时,移位运算符将起作用。 工作常数示例:https://play.golang.org/p/XRLL4FR8ZEl
const (
bucketCntBits = 3 // <---- This works
)
func main() {
bucketCnt := 1 << bucketCntBits
fmt.Println("Hello, playground", bucketCnt)
}
为什么常量可以工作,而文字对于移位运算符却不起作用?
最佳答案
<小时/>Go 1.13 Release Notes (September 2019)
Changes to the language
Per the signed shift counts proposal Go 1.13 removes the restriction that a shift count must be unsigned. This change eliminates the need for many artificial uint conversions, solely introduced to satisfy this (now removed) restriction of the << and >> operators.
invalid operation: 1 << bucketCntBits (shift count type int, must be unsigned integer)
对于 Go 1.13(2019 年 9 月)及更高版本,这不再是错误。
你的例子,
package main
import "fmt"
func main() {
bucketCntBits := 3
bucketCnt := 1 << bucketCntBits
fmt.Println(bucketCnt)
}
输出:
$ go version
go version devel +66ff373911 Sat Aug 24 01:11:56 2019 +0000 linux/amd64
$ go run shift.go
8
关于go - 使用数字文字但不使用数字常量的移位运算符会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737743/