Pass a slice as function parameter


As stated in The Effective Go:
"Slices hold references to an underlying array, and if you assign one slice to another, both refer to the same array. If a function takes a slice argument, changes it makes to the elements of the slice will be visible to the caller, analogous to passing a pointer to the underlying array."

This means if you modify the element of the slice without doing other operations (append, delete, insert ...), the caller can see the change. 
 
What if doing operations like append, cut, delete, insert to the slice in the function call?
It is a different story.  The builtin function append()  returns a slice which is different from the input. So if you do any of the above operations, it changes the reference of the original slice passed to the function. And in Golang, passing a variable means passing a copy. So the caller won't see the changes.
 
For example, https://play.golang.org/p/cIyM6dc6Ph.
package main

import (
    "fmt"
)

func test(s []int) {
    s[0] = 3
    s = append(s, 5)
}

func main() {
    m := []int{2}
    test(m)
    fmt.Println(m)
}
 
Run: 
[3] // can see the change of the existing element, but can't see the changes made by append.



  


Comments:

Write a comment
Anonymous

Captcha image

Reload

Type the number you see in the image above: