Created
March 24, 2021 09:43
-
-
Save erikcorry/5bcd95b916527969a4210a3aa32bd7a0 to your computer and use it in GitHub Desktop.
Golang slices sometimes alias their underlying array, and sometimes don't.
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
// Prints false, false, false, true, false, true, true, false, true. | |
package main | |
func main() { | |
for i := 0; i < 10; i++ { | |
println(doesItAlias(i)) | |
} | |
} | |
func doesItAlias(length int) bool { | |
a := []int{} | |
for i := 0; i < length; i++ { | |
a = append(a, i) | |
} | |
b := a[0:] | |
c := a[0:] | |
b = append(b, 42) | |
c = append(c, 103) | |
return b[length] == c[length] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment