Golang 创建切片的切片
在go语言中,切片是一个可变长度的数组,这意味着可以根据需要添加和删除值。在本文中,我们将使用两个示例创建切片的切片,切片的切片表示多个切片包含在一个切片中。在第一个示例中,我们将演示两种方式创建切片的切片,首先我们将使用一些值初始化切片的切片,然后使用第二种方式创建一个空的切片的切片,之后会在其中追加值。在第二个示例中,将使用make函数创建一个空的切片的切片,然后在其中追加值以获取输出。
语法
func make ([] type, size, capacity)
在go语言中,make函数用于创建一个数组/映射,它接受要创建的变量类型、大小和容量作为参数。
funcappend(slice, element_1, element_2…, element_N) []T
append函数用于向数组中添加值。它需要多个参数。第一个参数是我们要添加值的数组,其后是要添加的值。该函数返回包含所有值的数组的最终切片。
步骤
- 创建一个主包,并在程序中声明fmt(格式化包)包,其中main产生可执行代码,fmt帮助格式化输入和输出。
-
创建一个主函数,在该函数中创建一个整型切片的切片。
-
用一些值初始化切片,并使用Println函数将切片的切片打印到控制台上,其中ln表示换行。
-
然后,创建一个空的整型切片的切片,并使用Golang中的内置append方法向其中添加值。
-
然后,类似于上一步骤,将empty_slice打印到控制台上。
示例1
在此示例中,我们将创建一个主函数,在该函数中创建一个整型切片的切片,并向该切片的切片中添加值。然后,我们将创建一个空的切片,并使用append方法向其中添加值。通过这种方式,我们将演示如何创建切片的切片。
package main
import "fmt"
//Main function to execute the program
func main() {
slice_of_slices := [][]int{
[]int{10, 20, 30},
[]int{40, 50, 60},
[]int{70, 80, 90},
}
// Print the slice of slices
fmt.Println("The slice of slices is:")
fmt.Println(slice_of_slices)
// Create an empty slice of slices and append slices to it
empty_slice := [][]int{}
empty_slice = append(empty_slice, []int{1, 10, 2})
empty_slice = append(empty_slice, []int{3, 4, 5})
empty_slice = append(empty_slice, []int{6, 7, 8})
// Print the empty slice of slices with appended slices
fmt.Println(empty_slice)
}
输出
The slice of slices is:
[[10 20 30] [40 50 60] [70 80 90]]
[[1 10 2] [3 4 5] [6 7 8]]
示例2
在这个示例中,主函数中将创建一个空的切片,通过使用不同的切片和append方法向其中添加值。输出将使用fmt包在控制台上打印切片的切片。
package main
import "fmt"
func main() {
// Create an empty slice of slices
slice_of_slices := make([][]int, 0)
slice1 := []int{10, 20, 30}
slice2 := []int{40, 50, 60}
slice3 := []int{70, 80, 90}
slice_of_slices = append(slice_of_slices, slice1)
slice_of_slices = append(slice_of_slices, slice2)
slice_of_slices = append(slice_of_slices, slice3)
// Print the slice of slices on the console
fmt.Println("The slice of slices is:")
fmt.Println(slice_of_slices)
}
输出
The slice of slices is:
[[10 20 30] [40 50 60] [70 80 90]]
结论
我们执行和编译了使用两个示例创建切片的程序。在第一个示例中,我们创建了一个切片的切片,添加了值,并进一步创建了一个空的切片,然后我们给它添加了值。而在第二个示例中,我们创建了一个空的切片,并逐个往其中添加了值。