package main import ( "fmt" "reflect" ) /** * A little go program showing the information stored about a slice * as information in inserted into 2 different slices. The interesting * thing about the preallocated slice is that it is more efficient. * * The one that starts empty has to move the data 4 times * to do 9 insertions -- the slice initially has space fo zero items, * then, on first add it creates a slice to store 1 item * (no data move), next add creates slice with 2 spaces (MOVE), * next add 4 spaces (MOVE), fifth add creates a slice with 8 spaces * (MOVE), ... * * @author gtowell * created: July 14, 2022 * modified Oct 1 2022 gtowell added reflection to get the type **/ func main() { aa := make([]int, 0, 11) var bb []int fmt.Printf("bb is a slice of type %v\n", reflect.TypeOf(bb)) fmt.Printf("bb contains elements of type %v\n", reflect.TypeOf(bb).Elem()) fmt.Printf("aa loc %12p %d %d\n", aa, len(aa), cap(aa)) fmt.Printf("bb loc %12p %d %d\n", bb, len(bb), cap(bb)) fmt.Printf("\n") for i:=1; i<10; i++ { aa = append(aa, i) bb = append(bb, i) fmt.Printf("aa loc %p %d %d\n", aa, len(aa), cap(aa)) fmt.Printf("bb loc %p %d %d\n", bb, len(bb), cap(bb)) fmt.Printf("\n") } }