title: Capacity of slices in Go
body: <p>I have a question about the below code      </p>
  
  <pre><code>package main
  
  import "fmt"
  
  func main() {
      var a []int
      printSlice("a", a)
  
      // append works on nil slices.
      a = append(a, 0)
      printSlice("a", a)
  
      // the slice grows as needed.
      a = append(a, 1)
      printSlice("a", a)
  
      // we can add more than one element at a time.
      a = append(a, 2, 3, 4)
      printSlice("a", a)
  }
  
  func printSlice(s string, x []int) {
      fmt.Printf("%s len=%d cap=%d %v\n",
      s, len(x), cap(x), x)
  }       
  </code></pre>
  
  <p>I always guess what the result of running a piece of code will look like then run the code and check if my guess is correct. But this code resulted a little bit different from my guess:     </p>
  
  <p><strong>Result:</strong><br>
  <strong><em>On my local go tour server:</em></strong>    </p>
  
  <pre><code>a len=0 cap=0 []
  a len=1 cap=1 [0]
  a len=2 cap=2 [0 1]
  a len=5 cap=6 [0 1 2 3 4]      
  </code></pre>
  
  <p>Everything is ok until the last line but I don't get     </p>
  
  <pre><code>cap=6     
  </code></pre>
  
  <p>why not     </p>
  
  <pre><code>cap=5    
  </code></pre>
  
  <p>My opinion is I did not create slice with explicit capacity therefore my system gave it this value of <strong>6</strong>.    </p>
  
  <p><strong>2</strong>) But when I tried this same code on the golang tour server I get a little more diffferent result like this :     </p>
  
  <pre><code>a len=0 cap=0 []
  a len=1 cap=2 [0]
  a len=2 cap=2 [0 1]
  a len=5 cap=8 [0 1 2 3 4]   
  </code></pre>
  
  <p>What about <strong>cap=2</strong> on the second line and <strong>cap=8</strong> on the last line?</p>