Member-only story

Why Always Pass Slice by Reference in Golang

Simplify Complexity
1 min readJul 1, 2021

Example Code

package mainimport (
"fmt"
)
func main() {
slice:= make([]string, 1, 3)
slice[0] = "x"
func(slice []string){
slice =append(slice, "b")
slice =append(slice, "b")
fmt.Print(len(slice))
fmt.Println(slice)
}(slice)
fmt.Print(len(slice))
fmt.Println(slice)
}

The output of the above code is

3[x b b]
1[x]

A slice is passed by reference means passing the address of the buffer that stores the content of the slice.

However, metadata of the slice is still passed by value. The metadata is the size and capacity of the slice.

Explanation

The caller has maintained the size of the slice as 1 and capacity as 3.

The callee adds two new elements to the slice, changing size to 3. But the caller copy of the metadata still has a size value of 1.

Modified Code

package mainimport (
"fmt"
)
func main() {
slice:= make([]string, 1, 3)
slice[0] = "x"
func(slice *[]string){
*slice =append(*slice, "b")
*slice =append(*slice, "b")
fmt.Print(len(*slice))
fmt.Println(*slice)
}(&slice)
fmt.Print(len(slice))
fmt.Println(slice)
}

The output of the above code is:

3[x b b]
3[x b b]

Reference

https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b

--

--

Simplify Complexity
Simplify Complexity

Written by Simplify Complexity

Golang, Distributed Systems, File Systems, Python, C/C++, Linux

Responses (1)