Skip to content

Instantly share code, notes, and snippets.

@dulao5
Created August 20, 2018 02:39
Show Gist options
  • Save dulao5/c3926189a10f7579ada5befdd04e29a0 to your computer and use it in GitHub Desktop.
Save dulao5/c3926189a10f7579ada5befdd04e29a0 to your computer and use it in GitHub Desktop.
golang: slice append and cap
package main
import "fmt"
func main() {
slice := []int{1}
fmt.Printf("%v , len: %v , cap: %v\n", &slice[0], len(slice), cap(slice))
oldCap := cap(slice)
for i := 0; i<10000; i++ {
slice = append(slice, i)
if cap(slice) > oldCap {
fmt.Printf("%v , len: %v , cap: %v\n", &slice[0], len(slice), cap(slice))
oldCap = cap(slice)
}
}
}
@dulao5
Copy link
Author

dulao5 commented Aug 20, 2018

output


0xc420016080 , len: 1 , cap: 1
0xc4200160b0 , len: 2 , cap: 2
0xc420018260 , len: 3 , cap: 4
0xc420012100 , len: 5 , cap: 8
0xc42008e000 , len: 9 , cap: 16
0xc420090000 , len: 17 , cap: 32
0xc420092000 , len: 33 , cap: 64
0xc420094000 , len: 65 , cap: 128
0xc420096000 , len: 129 , cap: 256
0xc420098000 , len: 257 , cap: 512
0xc42009a000 , len: 513 , cap: 1024
0xc42009c000 , len: 1025 , cap: 1280
0xc4200a6000 , len: 1281 , cap: 1696
0xc4200b0000 , len: 1697 , cap: 2304
0xc4200c2000 , len: 2305 , cap: 3072
0xc4200c8000 , len: 3073 , cap: 4096
0xc4200d0000 , len: 4097 , cap: 5120
0xc4200da000 , len: 5121 , cap: 7168
0xc4200e8000 , len: 7169 , cap: 9216
0xc4200fa000 , len: 9217 , cap: 12288

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