Lists

A slice is a segment of an array whose length can change.

The major difference between an array and a slice is that with thearray you need to know the size up front. In Go, there is no way toequally easily add values to an existing slice so if you want toeasily add values, you can initialize a slice at a max length andincrementally add things to it.

Python

  1. # initialize list
  2. numbers = [0] * 5
  3. # change one of them
  4. numbers[2] = 100
  5. some_numbers = numbers[1:3]
  6. print some_numbers # [0, 100]
  7. # length of it
  8. print len(numbers) # 5
  9.  
  10. # initialize another
  11. scores = []
  12. scores.append(1.1)
  13. scores[0] = 2.2
  14. print scores # [2.2]

Go

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. // initialized array
  7. var numbers [5]int // becomes [0, 0, 0, 0, 0]
  8. // change one of them
  9. numbers[2] = 100
  10. // create a new slice from an array
  11. some_numbers := numbers[1:3]
  12. fmt.Println(some_numbers) // [0, 100]
  13. // length of it
  14. fmt.Println(len(numbers))
  15.  
  16. // initialize a slice
  17. var scores []float64
  18. scores = append(scores, 1.1) // recreate to append
  19. scores[0] = 2.2 // change your mind
  20. fmt.Println(scores) // prints [2.2]
  21.  
  22. // when you don't know for sure how much you're going
  23. // to put in it, one way is to
  24. var things [100]string
  25. things[0] = "Peter"
  26. things[1] = "Anders"
  27. fmt.Println(len(things)) // 100
  28. }