Created
June 4, 2019 00:57
-
-
Save chrisbloom7/0d418faf5d9d27dd94ab1274fe6cd9ca to your computer and use it in GitHub Desktop.
Surprising behavior when passing arrays and slices to functions in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
var a1 = [3]int{1, 2, 3} | |
var s1 = a1[0:3] | |
func main() { | |
fmt.Println("array at beginning", a1) | |
fmt.Println("slice at beginning", s1) | |
passingByVal() | |
fmt.Println("array at end", a1) | |
fmt.Println("slice at end", s1) | |
} | |
func passingByVal() { | |
fmt.Println(" array before outer calls", a1) | |
fmt.Println(" slice before outer calls", s1) | |
aByVal(a1) | |
fmt.Println(" array between outer calls", a1) | |
fmt.Println(" slice between outer calls", s1) | |
sByVal(s1) | |
fmt.Println(" array after outer calls", a1) | |
fmt.Println(" slice after outer calls", s1) | |
} | |
func aByVal(a2 [3]int) { | |
fmt.Println(" array before inner call", a2) | |
a2[0] = 4 | |
fmt.Println(" array after inner call", a2) | |
} | |
func sByVal(s2 []int) { | |
fmt.Println(" slice before inner call", s2) | |
s2[1] = 5 | |
s2 = append(s2, 6) | |
fmt.Println(" slice after inner call", s2) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
array at beginning [1 2 3] | |
slice at beginning [1 2 3] | |
array before outer call [1 2 3] | |
slice before outer call [1 2 3] | |
array before inner call [1 2 3] | |
array after inner call [4 2 3] | |
array between outer calls [1 2 3] | |
slice between outer calls [1 2 3] | |
slice before inner call [1 2 3] | |
slice after inner call [1 5 3 6] | |
array after outer call [1 5 3] | |
slice after outer call [1 5 3] | |
array at end [1 5 3] | |
slice at end [1 5 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment