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

我在 go 中进行移位操作时遇到错误,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)

}

为什么常量可以工作,而文字却不能用于移位运算符?


弑天下
浏览 130回答 3
3回答

慕容3067478

Go 1.13 发行说明(2019 年 9 月)语言的变化根据已签名的班次计数提案, Go 1.13 删除了班次计数必须无符号的限制。此更改消除了对许多人工 uint 转换的需要,这些转换仅仅是为了满足 << 和 >> 运算符的此(现已删除)限制而引入的。invalid operation: 1 << bucketCntBits (shift count type int, must be unsigned integer)对于 Go 1.13(2019 年 9 月)及更高版本,这不再是错误。你的例子,package mainimport "fmt"func main() {    bucketCntBits := 3    bucketCnt := 1 << bucketCntBits    fmt.Println(bucketCnt)}输出:$ go versiongo version devel +66ff373911 Sat Aug 24 01:11:56 2019 +0000 linux/amd64$ go run shift.go8

慕标5832272

或者,您可以将类型uint8, uint16,uint32或强制转换uint64为整数文字。例如,func main() {&nbsp; &nbsp; bucketCntBits := uint32(3)&nbsp; &nbsp; bucketCnt&nbsp; &nbsp; &nbsp;:= 1 << bucketCntBits&nbsp; &nbsp; fmt.Println(bucketCnt)}输出:8

慕雪6442864

使用math/bits包你可以做这样的事情:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/bits")func main() {&nbsp; &nbsp; bucketCntBits := 3&nbsp; &nbsp; bucketCnt&nbsp; &nbsp; &nbsp;:= bits.RotateLeft(1, bucketCntBits)&nbsp; &nbsp; fmt.Println("Hello, playground", bucketCnt)}https://play.golang.org/p/fVK2xysL896
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go