Unlike an array, the length of a slice can be modified at runtime, which is equivalent to an array with variable length.
The type []T
is a slice of element type T.
A slice reference to a continuous segment of an array. the expression.
var slice1 []type = array1[start:end]
slice1 is a subset of the elements of array1 indexed from start to end-1.
切片也可以以类似于数组的方式初始化。
下面的示例创建一个长度为 5 的数组并创建一个相关的切片。
var slice2 = []int{2, 3, 5, 7, 11}
The following is a complete code example.
package main
import "fmt"
func main() {
var slice1 []int
fmt.Println(slice1)
}
Below is the program output:
[]