Gaaker Go

Golang Use make to create a slice

The built-in function make can be used to create slices.

The make function allocates an array with zero-valued elements and returns a slice that references the array:

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

The built-in function make has an optional third parameter to specify the capacity.

b := make([]int, 3, 5)

The slice b has a length of 3 and a capacity of 5.

The following is a complete code example.

package main

import "fmt"

func main() {
	a := make([]int, 10, 20)
	printSlice(a)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

Below is the program output:

len=10 cap=20 [0 0 0 0 0 0 0 0 0 0]
< Use make to create a slice Use make to create a slice >