array_slices.go 926 B

1234567891011121314151617181920212223242526272829303132
  1. package main
  2. import "fmt"
  3. func main() {
  4. var arr1 [6]int
  5. var slice1 []int = arr1[2:5] // item at index 5 not included!
  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 bound out of range
  26. }