Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in shift operator using numeric literals but not with numeric constant

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?

like image 861
Aditya Singh Avatar asked Aug 31 '19 11:08

Aditya Singh


1 Answers

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
like image 54
peterSO Avatar answered Oct 28 '22 20:10

peterSO