Creating a slice with make

Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.

The make function allocates a zeroed array and returns a slice that refers to that array:

  1. a := make([]int, 5) // len(a)=5

To specify a capacity, pass a third argument to make:

  1. b := make([]int, 0, 5) // len(b)=0, cap(b)=5
  2.  
  3. b = b[:cap(b)] // len(b)=5, cap(b)=5
  4. b = b[1:] // len(b)=4, cap(b)=4

making-slices.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. a := make([]int, 5)
  5. printSlice("a", a)
  6. b := make([]int, 0, 5)
  7. printSlice("b", b)
  8. c := b[:2]
  9. printSlice("c", c)
  10. d := c[2:5]
  11. printSlice("d", d)
  12. }
  13. func printSlice(s string, x []int) {
  14. fmt.Printf("%s len=%d cap=%d %v\n",
  15. s, len(x), cap(x), x)
  16. }