diff --git a/chapter-3-composite-types/02_slices.go b/chapter-3-composite-types/02_slices.go index 374a26c..3ef8b89 100644 --- a/chapter-3-composite-types/02_slices.go +++ b/chapter-3-composite-types/02_slices.go @@ -13,4 +13,68 @@ func main() { x = []int{1, 5: 4, 6, 10: 20, 11} fmt.Println(x) + fmt.Println() + + // access last element in a slice + fmt.Println(x[len(x)-1]) + fmt.Println() + + // empty slice is nil value (no type) + // can only compare slices to nil + var y []int + fmt.Println(y == nil) + fmt.Println() + + // this notiation declares a nil slice + var y0 []int + fmt.Println("y0", y0 == nil) + // this notation declares an empty slice literal + var y1 = []int{} + fmt.Println("y1", y1 == nil) + // they are the same value ([]), but one is nil and one is not! + fmt.Println(y0, y1) + fmt.Println() + + // can append more than one at a time + y = append(y, 1) + y = append(y, 2, 3) + fmt.Println(y) + fmt.Println() + + // can use ... notation to unpack + x = append(x, y...) + fmt.Println(x) + fmt.Println() + + // print the capacity of the slize (the memory reserved) + // show how it increases as you add more + var z []int + fmt.Println(z, len(z), cap(z)) + z = append(z, 10) + fmt.Println(z, len(z), cap(z)) + z = append(z, 20) + fmt.Println(z, len(z), cap(z)) + z = append(z, 30) + fmt.Println(z, len(z), cap(z)) + z = append(z, 40) + fmt.Println(z, len(z), cap(z)) + z = append(z, 50) + fmt.Println(z, len(z), cap(z)) + fmt.Println() + + // make specifies type, length, capacity + + // slice of ints length 5 (5 0's) + // don't use append with this as youll get [0,0,0,0,0,$append_val] + a := make([]int, 5) + fmt.Println(a) + fmt.Println() + + // slice of ints length 0 capcity 10 + b := make([]int, 0, 10) + fmt.Println(b) + // can use append with this + b = append(b, 1) + fmt.Println(b, len(b), cap(b)) + fmt.Println() }