douliedai4838 2019-08-31 11:44
浏览 215
已采纳

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

I am getting error while doing a shift operation in go with invalid operation: 1 << bucketCntBits (shift count type int, must be unsigned integer) error on trying to declare a literal in go inside main() body Failing literal example: https://play.golang.org/p/EqI-yag5yPp

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

When I declare the shift count as a constant, the shift operator works. Working constant example: https://play.golang.org/p/XRLL4FR8ZEl

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

func main() {

    bucketCnt     := 1 << bucketCntBits
    fmt.Println("Hello, playground", bucketCnt)
}

Why does the constant work while the literal doesn't for the shift operator?

  • 写回答

3条回答 默认 最新

  • duanjing3656 2019-08-31 13:31
    关注

    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)
    

    This is no longer an error for Go 1.13 (September 2019) and later.

    Your example,

    package main
    
    import "fmt"
    
    func main() {
        bucketCntBits := 3
        bucketCnt := 1 << bucketCntBits
        fmt.Println(bucketCnt)
    }
    

    Output:

    $ go version
    go version devel +66ff373911 Sat Aug 24 01:11:56 2019 +0000 linux/amd64
    
    $ go run shift.go
    8
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档