Monthly Archives: August 2018

Go (Golang) Array Specialities

If calling a function in go with an array as parameter, „strange“ things happen from time to time. Some call them pitfalls – anyway it’s a must know for golang programming.

I will share some experiments:

https://play.golang.org/p/snqZWeqJWpw

package main

import (
  "fmt"
)

func shortenRef(a *[]int) {
  copy(*a, (*a)[3:])
  *a = (*a)[:3]
  fmt.Println(*a, len(*a))
  *a = make([]int, 10)
  fmt.Println(*a, len(*a))
}

func shortenArr(a []int) {
  copy(a, a[3:])
  a = a[:3]
  fmt.Println(a, len(a))
  a = make([]int, 10)
  fmt.Println(a, len(a))
}

func main(){
  a := []int{0,1,2,3,4,5,6,7,8,9}
  shortenRef(&a)
  fmt.Printf("call shortenRef(&a): %v len: %v\n", a, len(a))
  a = []int{0,1,2,3,4,5,6,7,8,9}
  shortenArr(a)
  fmt.Printf("call shortenArr(a): %v len: %v\n", a, len(a))
}

OUTPUT:

3 4 5] 3
[0 0 0 0 0 0 0 0 0 0] 10
call shortenRef(&a): [0 0 0 0 0 0 0 0 0 0] len: 10
[3 4 5] 3
[0 0 0 0 0 0 0 0 0 0] 10
call shortenArr(a): [3 4 5 6 7 8 9 7 8 9] len: 10