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

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

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示