dongshan4878 2018-10-30 05:45
浏览 282
已采纳

如何在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?

  • 写回答

1条回答 默认 最新

  • douchengchen7959 2018-10-30 05:49
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?