[Go] Slice

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

The type []T is a slice with elements of type T.

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

a[low : high]

This selects a half-open range which includes the first element, but excludes the last one.

The following expression creates a slice which includes elements 1 through 3 of a:

a[1:4]

 

package main

import "fmt"

func main() {
	primes := [6]int{2, 3, 5, 7, 11, 13}
	var s []int = primes[1:4]
	newS := append(s, 14, 15, 16)
	fmt.Println(s, len(s), cap(s)) // [3 5 7] 3 5
	fmt.Println(newS, len(newS), cap(newS)) // [3 5 7 14 15 16] 6 10
}

 

posted @ 2022-09-05 14:11  Zhentiw  阅读(17)  评论(0编辑  收藏  举报