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
- # initialize list
- numbers = [0] * 5
- # change one of them
- numbers[2] = 100
- some_numbers = numbers[1:3]
- print some_numbers # [0, 100]
- # length of it
- print len(numbers) # 5
- # initialize another
- scores = []
- scores.append(1.1)
- scores[0] = 2.2
- print scores # [2.2]
Go
- package main
- import "fmt"
- func main() {
- // initialized array
- var numbers [5]int // becomes [0, 0, 0, 0, 0]
- // change one of them
- numbers[2] = 100
- // create a new slice from an array
- some_numbers := numbers[1:3]
- fmt.Println(some_numbers) // [0, 100]
- // length of it
- fmt.Println(len(numbers))
- // initialize a slice
- var scores []float64
- scores = append(scores, 1.1) // recreate to append
- scores[0] = 2.2 // change your mind
- fmt.Println(scores) // prints [2.2]
- // when you don't know for sure how much you're going
- // to put in it, one way is to
- var things [100]string
- things[0] = "Peter"
- things[1] = "Anders"
- fmt.Println(len(things)) // 100
- }