Koepnick

arrays and slices

Jan 15th, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.85 KB | None | 0 0
  1. // Arrays are defined by [int]type
  2. // Lengths are immutable!
  3. a := [3]int
  4. a[0] = 1
  5. a[1] = 2
  6. a[2] = 3
  7. a[3] = 4
  8. a[4] = 5
  9.  
  10. // We can use literals
  11. a := [3]int{1, 2, 3}
  12.  
  13. // Slices are pointers to array members
  14. a[2:4]   // [3 4]
  15. a[:3]    // [1 2 3]
  16. a[4:]    // [5]
  17.  
  18. // We can use make to initialize a slice with an implicit array
  19. a := make([]int, 5)      // [0, 0, 0, 0, 0]
  20. cap(a)                   // 5
  21. len(a)                   // 5
  22. a := make([]int, 5, 10)  // [0, 0, 0, 0, 0, nil, nil, nil, nil, nil]
  23. cap(a)                   // 10
  24. len(a)                   // 5
  25.  
  26. // Slices can be appended to without worry about the immutable length
  27. a := make([]int, 5)
  28. a = append(a, 6)         // [0 0 0 0 0 6]
  29.  
  30. // Multidimensionality
  31. matrix := [][]int{
  32.   []int{0, 0, 1},
  33.   []int{0, 1, 0},
  34.   []int{1, 0, 0},
  35. }
  36. matrix[2][2] = 10 // [[0 0 1][0 1 0][1 0 1]]
Add Comment
Please, Sign In to add comment