Skip to content

Instantly share code, notes, and snippets.

@erikcorry
Created March 24, 2021 09:43
Show Gist options
  • Save erikcorry/5bcd95b916527969a4210a3aa32bd7a0 to your computer and use it in GitHub Desktop.
Save erikcorry/5bcd95b916527969a4210a3aa32bd7a0 to your computer and use it in GitHub Desktop.
Golang slices sometimes alias their underlying array, and sometimes don't.
// 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