array_slices.go 861 B

123456789101112131415161718192021222324252627282930313233
  1. package main
  2. import "fmt"
  3. func main() {
  4. var arr1 [6]int
  5. var slice1 []int = arr1[2:5] // index 5 niet meegerekend!
  6. // load the array with integers: 0,1,2,3,4,5
  7. for i := 0; i < len(arr1); i++ {
  8. arr1[i] = i
  9. }
  10. // print the slice:
  11. for i := 0; i < len(slice1); i++ {
  12. fmt.Printf("Slice at %d is %d\n", i, slice1[i])
  13. }
  14. fmt.Printf("The length of arr1 is %d\n", len(arr1))
  15. fmt.Printf("The length of slice1 is %d\n", len(slice1))
  16. fmt.Printf("The capacity of slice1 is %d\n", cap(slice1))
  17. // grow the slice:
  18. slice1 = slice1[0:4]
  19. for i := 0; i < len(slice1); i++ {
  20. fmt.Printf("Slice at %d is %d\n", i, slice1[i])
  21. }
  22. fmt.Printf("The length of slice1 is %d\n", len(slice1))
  23. fmt.Printf("The capacity of slice1 is %d\n", cap(slice1))
  24. // grow the slice beyond capacity:
  25. // slice1 = slice1[0:7 ] // panic: runtime error: slice bounds out of range
  26. }