在 Go 语言中, Slice是一种关键数据类型,与数组相比,它功能强大且灵活。 Slice 是对数组的抽象,克服了数组的局限性,例如动态获取大小或创建自己的子数组,因此比传统数组更方便使用。它就像一个具有索引值和长度的数组,但是切片的大小是调整大小的,它们不像数组那样是固定大小的。切片上只存储一个相似类型的元素,不同类型的元素不能存储在同一个切片上。
切片是通过指定两个索引(下限和上限)形成的,由冒号分隔,如下所示:
arr[low_bound : high_bound]
This includes the low_bound, but excludes the high_bound, where the smallest value of low_bound can be 0 and largest value of high_bound can be the length of arr array.
为了制作切片,我们可以将它们组合成类似于二维数组的多维数据结构。这是通过使用名为make()的函数来完成的,该函数创建一个非零长度的空切片。这在以下示例中显示:
Go
package main
import (
"fmt"
)
// main function
func main() {
// declaring a slice of slices of
// type integer with a length of 3
slice_of_slices := make([][]int , 3)
for i := 0; i < 3; i++ {
// looping through the slice to declare
// slice of slice of length 3
slice_of_slices[i] = make([]int, 3)
// assigning values to each
// slice of a slice
for j := 0; j < 3; j++{
slice_of_slices[i][j] = i * j
}
}
// printing the slice of slices matrix
for i := 0; i < 3; i++ {
fmt.Println(slice_of_slices[i])
}
fmt.Println("Slice of slices: ", slice_of_slices)
}
Go
package main
import (
"fmt"
)
// main function
func main() {
// declaring a slice of slices of
// type integer with a length of 3
slice_of_slices := make([][]int , 3)
for i := 0; i < 3; i++ {
new_length := i * 2 + 1
// looping through the slice to declare
// slice of slice of a variable length
slice_of_slices[i] = make([]int, new_length)
// assigning values to each
// slice of a slice
for j := 0; j < new_length; j++{
slice_of_slices[i][j] = i * j + 1
}
}
// printing the slice of slices matrix
for i := 0; i < 3; i++ {
fmt.Println(slice_of_slices[i])
}
fmt.Println("Slice of slices: ", slice_of_slices)
}
输出:
[0 0 0]
[0 1 2]
[0 2 4]
Slice of slices: [[0 0 0] [0 1 2] [0 2 4]]
由于切片的动态特性,可以有可变的切片切片。这在下面的示例中显示:
去
package main
import (
"fmt"
)
// main function
func main() {
// declaring a slice of slices of
// type integer with a length of 3
slice_of_slices := make([][]int , 3)
for i := 0; i < 3; i++ {
new_length := i * 2 + 1
// looping through the slice to declare
// slice of slice of a variable length
slice_of_slices[i] = make([]int, new_length)
// assigning values to each
// slice of a slice
for j := 0; j < new_length; j++{
slice_of_slices[i][j] = i * j + 1
}
}
// printing the slice of slices matrix
for i := 0; i < 3; i++ {
fmt.Println(slice_of_slices[i])
}
fmt.Println("Slice of slices: ", slice_of_slices)
}
输出:
[1]
[1 2 3]
[1 3 5 7 9]
Slice of slices: [[1] [1 2 3] [1 3 5 7 9]]