title: How to declare uint8 in for-loop initialization, as var is not allowed in for loop initialization
body: <p>I am writing following code to calculate Population Count as below:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
  )
  
  func main() {
      var pc [256]byte
  
      for i := range pc {
          pc[i] = pc[i/2] + byte(i&amp;1)
      }
  
      var x uint64 = 65535
      var population uint8
  
      for i := 0; i &lt; 8; i++ {
          population  = population + pc[byte(x&gt;&gt;(i*8))]
      }
  
      fmt.Printf("Population Count: %d", population)
  }
  </code></pre>
  
  <p>On compilation I get following error:</p>
  
  <blockquote>
    <p>prog.go:19:39: invalid operation: x >> (i * 8) (shift count type int,
    must be unsigned integer)</p>
  </blockquote>
  
  <p>The problem is with the variable <code>i</code> which is declared while initializing the for loop. The shorthand initialization of <code>i</code> makes it of type <code>int</code> which in internally of type <code>signed int32</code>. This is why the following line:</p>
  
  <pre><code>population  = population + pc[byte(x&gt;&gt;(i*8))]
  </code></pre>
  
  <p>is causing the problem. Because shift operator <code>&gt;&gt;</code> is expecting only unsigned integer, but the expression <code>i*8</code> results into <code>int</code> which is internally <code>signed int32</code>.</p>
  
  <p>As <code>var</code> can not be used in <code>for</code> initialization. </p>
  
  <pre><code>for var i uint8 = 0; i &lt; 8; i++ { ... }
  </code></pre>
  
  <blockquote>
    <p>syntax error: var declaration not allowed in for initializer</p>
  </blockquote>
  
  <p>I can declare variable <code>i</code> outside of <code>for loop</code>, but I do not find it clean and readable.</p>
  
  <p>What should be the clean way to achieve the same?</p>