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.