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

标签 go constants literals

我在 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/

相关文章:

python - Perl 对应的 Python 前缀 r"text"的字符串文字?

c - 如何分配1位值?

go - new-ed 结构的返回类型是什么?

image - Golang PNG 颜色操作不会达到 255

go - 使用什么系统调用来获取某些 RTF_* 标志的值

javascript - 我有什么理由不使用 "let"吗?

bash - 在 go 中使用 "redirecting of an output from a subshell"语句运行 shell 命令

Ruby - 使用某些函数进行常量初始化会产生 NoMethodError

c - 对于任何类型,使用 const void* 代替 void*

python - 字符串变量作为 lxml.builder 中的 href