Created
June 12, 2021 20:23
-
-
Save pavelanni/60b73f73a7512a2cc1c44632ea04cffd to your computer and use it in GitHub Desktop.
This file contains 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" | |
func inner(s []int) { | |
s[len(s)-1] = 999 | |
} | |
func inner2(s []int) { | |
s[0] = 9 | |
s = append(s, 9999) | |
s[1] = 99 | |
fmt.Println(s) // prints [9,99,999,9999], of course | |
} | |
func main() { | |
s1 := []int{1, 2, 3} | |
fmt.Println(s1) // prints [1,2,3], of course | |
inner(s1) // this changes the slice in-place | |
fmt.Println(s1) // prints [1,2,999] | |
inner2(s1) | |
fmt.Println(s1) // prints 9, 2, 999 because s[0] was changed before appending | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is interesting: in Go, if you pass a slice into a function you can change the original slice inside the function -- if you don't expand the slice! As soon as you append() something to the slice, it creates a copy and now you are changing the copy, not the original!
(When reading "Learning Go" by Jon Bodner)