Skip to content

Instantly share code, notes, and snippets.

@mnrtks
Created January 14, 2015 09:21
Show Gist options
  • Save mnrtks/a487f2b6f2a6127c16ad to your computer and use it in GitHub Desktop.
Save mnrtks/a487f2b6f2a6127c16ad to your computer and use it in GitHub Desktop.
Go slice behavior
package main
import "fmt"
func main() {
hoge := make([]int, 10, 10)
show(hoge)
for i := range hoge {
hoge[i] = i
}
hoge = hoge[:5]
show(hoge)
hoge = hoge[0:cap(hoge)]
show(hoge)
hoge = append(hoge[:5], hoge[6:]...)
show(hoge)
hoge = append(hoge, 10)
show(hoge)
hoge = append(hoge, 11) // reallocate and copy
show(hoge)
hoge = append(hoge[:0], hoge[3:]...)
show(hoge)
}
func show(s []int) {
fmt.Printf("%p: %v (len:%d, cap:%d)\n", s, s, len(s), cap(s))
}
@mnrtks
Copy link
Author

mnrtks commented Jan 14, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment