Gaaker Go

Golang Length and capacity of slices

The slice has a length and a capacity.

The length of a slice is the number of its elements.

The capacity of a slice is the length of the original array to which it refers.

The length and capacity of the slice s can be obtained through the built-in functions len(s) and cap(s).

The following is a complete code example.

package main

import "fmt"

func main() {
	s := []int{2, 3, 5, 7, 11, 13}
	printSlice(s)

	// 截取切片使其长度为 0
	s = s[:0]
	printSlice(s)

	// 拓展其长度
	s = s[0:4]
	printSlice(s)

	// 舍弃前两个值
	s = s[2:6]
	printSlice(s)
}

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

Below is the program output:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=4 cap=4 [5 7 11 13]
< Length and capacity of slices Length and capacity of slices >