如何在for循环初始化中声明uint8,因为for循环初始化中不允许使用var

如何在for循环初始化中声明uint8,因为for循环初始化中不允许使用var

问题描述:

I am writing following code to calculate Population Count as below:

package main

import (
    "fmt"
)

func main() {
    var pc [256]byte

    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }

    var x uint64 = 65535
    var population uint8

    for i := 0; i < 8; i++ {
        population  = population + pc[byte(x>>(i*8))]
    }

    fmt.Printf("Population Count: %d", population)
}

On compilation I get following error:

prog.go:19:39: invalid operation: x >> (i * 8) (shift count type int, must be unsigned integer)

The problem is with the variable i which is declared while initializing the for loop. The shorthand initialization of i makes it of type int which in internally of type signed int32. This is why the following line:

population  = population + pc[byte(x>>(i*8))]

is causing the problem. Because shift operator >> is expecting only unsigned integer, but the expression i*8 results into int which is internally signed int32.

As var can not be used in for initialization.

for var i uint8 = 0; i < 8; i++ { ... }

syntax error: var declaration not allowed in for initializer

I can declare variable i outside of for loop, but I do not find it clean and readable.

What should be the clean way to achieve the same?

The Go Programming Language Specification

Variable declarations

... each variable is given the type of the corresponding initialization value in the assignment.


i := uint(0). For example,

package main

import (
    "fmt"
)

func main() {
    var pc [256]byte

    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }

    var x uint64 = 65535
    var population uint8

    for i := uint(0); i < 8; i++ {
        population = population + pc[byte(x>>(i*8))]
    }

    fmt.Printf("Population Count: %d", population)
}

Playground: https://play.golang.org/p/H_4cn9w_dOq

Output:

Population Count: 16