aren't arrays in Go supposed to behave like single variables?

The issue here is that I discovered that arrays in go language don’t behave the same way of a simple variable when we send it to a function as a parameter.
let’s compare those Two examples :

func do(vis bool) {
    vis = false
}

func main() {
    vis := true
    fmt.Println(vis)
    do(vis)
    fmt.Println(vis)
}

In the above example, the function didn’t change the global variable vis so it remained true as it was from its initialization. As you can see in the following output.

true
true

However, in the second example, I discovered a total different behavior:

func do(vis []bool) {
    for idx := range vis {
        vis[idx] = false
    }
}

func main() {
    vis := []bool{true, true, true, true}
    fmt.Println(vis)
    do(vis)
    fmt.Println(vis)
}

And this is the output:

[true true true true]
[false false false false]

the content of the vis has remarkably changed although I didn’t pass the address of the array so that it can change it.
Can you please explain why the variable is changed like that?

>Solution :

You did not pass an array to the function, you passed a slice.

An array and a slice are two different things in go. An array behaves as you expected: when you pass an array, a copy of it is passed to the function, and the function operates on the copy. Same thing happens with the slice, a copy of the slice is passed to the function. However, a slice is actually a small data structure that points to an underlying array. Thus, the function modifying the slice can change the array pointed to by the slice.

If the function appends to that slice, for instance, the appended slice will not be visible to the caller.

Leave a Reply