Go语言程序:创建切片切片


Go 语言中的切片是一个可变长度数组,这意味着可以根据需要向其中添加和删除值。在本文中,我们将通过两个示例来创建切片切片,切片切片意味着一个切片中包含多个切片。在第一个示例中,我们将以两种方式演示切片切片的创建,首先我们将用一些值初始化切片切片,在第二种方式中,将创建一个空的切片切片,稍后将在其中追加值。在第二个示例中,将使用 make 函数创建一个空的切片切片,然后向其中追加值以获取输出。

语法

func make ([] type, size, capacity)

Go 语言中的 make 函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。

funcappend(slice, element_1, element_2…, element_N) []T

append 函数用于向数组切片添加值。它接受多个参数。第一个参数是要向其中添加值的数组,后跟要添加的值。然后,该函数返回包含所有值的数组的最终切片。

算法

  • 创建一个 package main 并声明程序中的 fmt(格式化包)包,其中 main 生成可执行代码,fmt 帮助格式化输入和输出。

  • 创建一个 main 函数,并在该函数中创建一个整数类型的切片切片

  • 使用一些值初始化切片,并使用 Println 函数在控制台上打印切片切片,其中 ln 表示换行

  • 然后,创建一个空的整数类型的切片切片,并使用 append 方法(Golang 中的内置函数)向切片切片中追加值

  • 然后,类似于我们在上一步中所做的那样,在控制台上打印 empty_slice

示例 1

在本例中,我们将创建一个 main,并在该 main 中,我们将创建一个切片切片并在切片切片中添加值,在第二种方式中,我们将创建一个空切片并使用 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

在本例中,在 main 函数中将创建一个空的切片切片,其中将通过使用不同的切片和 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]]

结论

我们使用两个示例执行并编译了创建切片切片的程序。在第一个示例中,我们创建了一个切片切片,在其中添加了值,并进一步创建了一个空切片,我们在其中添加了值。然后,在第二个示例中,我们创建了一个空切片并在其中分别添加了值。

更新于: 2023年7月20日

253 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.