P.An
P.An

Reputation: 353

Passing arrays as function arguments

I expected the following code snippet either to produce a as {0x01, 0x02} (pass by value) or as {0x03, 0x02, 0x01} (pass by reference). Strangely, it produces the output as {0x03, 0x02}. Could you please help me understand why is that?

package main

import "fmt"

func test1(t []byte) {
    t[0] = 0x03
    t = append(t, 0x01 )
}

func main() {
    a := []byte{0x01, 0x02 }
    test1(a)
    _ = a
    fmt.Printf("%v", a)
}

Upvotes: 3

Views: 141

Answers (2)

Viktor Simkó
Viktor Simkó

Reputation: 2627

In Go []byte is not an array, it's a byte slice.

What happened is that the size of a was 2, and because of that, after its first element was changed to 3, append allocated a new bigger slice - and t was set to the address of the new slice that was allocated, but that doesn't affect the a in main.

From A Tour of Go about append:

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

Upvotes: 6

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

The slice header is passed by value, but it references the same backing array. So when you change the first value it is changed in the original array as well. When you call append a new slice header is generated and written to the space occupied by the original argument value thus staying local to the method.

Upvotes: 1

Related Questions