Last active
January 13, 2018 22:29
-
-
Save sunho/40035e498007f17f43950e1804d4c332 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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