Skip to content

Instantly share code, notes, and snippets.

@sunho
Last active January 13, 2018 22:29
Show Gist options
  • Select an option

  • Save sunho/40035e498007f17f43950e1804d4c332 to your computer and use it in GitHub Desktop.

Select an option

Save sunho/40035e498007f17f43950e1804d4c332 to your computer and use it in GitHub Desktop.
slice := make([]int, 10, 15)
fmt.Printf("len: %d, cap: %d\n", len(slice), cap(slice))
newSlice := make([]int, len(slice), 2*cap(slice))
for i := range slice {
newSlice[i] = slice[i]
}
slice = newSlice
func Extend(slice []int, element int) []int {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]int, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment