Go語言程式初始化切片
在本文中,我們將學習如何透過多種方法和示例來初始化切片。切片就像陣列一樣,是一系列元素的序列。陣列是固定長度的元素序列,而切片是動態陣列,這意味著它的值不是固定的,可以更改。切片比陣列更高效、更快,而且它們是按引用傳遞而不是按值傳遞。讓我們透過示例學習如何執行它。
演算法
步驟 1 − 建立一個名為 main 的包,並在程式中宣告 fmt(格式化包)。其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。
步驟 2 − 建立一個 main 函式,並在該函式中使用 make 函式初始化一個切片,該函式有兩個引數:長度和容量。
步驟 3 − 在控制檯上列印使用 make 函式初始化的切片。
步驟 4 − 使用 fmt.Println() 函式執行列印語句,其中 ln 指的是換行。
語法
func make ([] type, size, capacity)
Go 語言中的 make 函式用於建立陣列/對映,它接受要建立的變數型別、其大小和容量作為引數。
func append(slice, element_1, element_2…, element_N) []T
append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要向其新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。
使用 Make 函式
在這個示例中,我們將學習如何使用 make 函式初始化切片。這是一個內建函式,其工作原理如下所述。讓我們瞭解一下它是如何透過演算法和程式碼來解決這個問題的。
示例
package main import "fmt" func main() { slice := make([]int, 2, 4) // create slice using make function fmt.Println("The slice created here has a length of:", slice) //print slice }
輸出
The slice created here has a length of: [0 0]
使用簡寫宣告
在這個示例中,我們將學習如何使用簡寫宣告初始化切片。建立的切片將使用 Go 語言中的列印語句在控制檯上列印。讓我們透過演算法和程式碼來了解這個概念。
示例
package main import "fmt" func main() { // creates a slice with elements slice := []int{1, 2, 3} fmt.Println("The slice created here is:") fmt.Println(slice) // print the slice }
輸出
The slice created here is: [1 2 3]
使用 Append 宣告
在這個示例中,我們將使用 append 函式初始化切片,其功能描述如下。在這裡,讓我們藉助演算法和程式碼來理解這個概念。
示例
package main import "fmt" func main() { var slice []int slice = append(slice, 1) //fill the elements in slice using append function slice = append(slice, 2) slice = append(slice, 3) fmt.Println("The slice created is:") fmt.Println(slice) // print the slice }
輸出
The slice created is: [1 2 3]
在 Append 函式中使用 For 迴圈
在這個示例中,我們將使用 for 迴圈中的 append 函式來初始化切片。使用迴圈可以幫助我們為切片分配元素。讓我們藉助演算法和程式碼來了解它。
示例
package main import "fmt" func main() { // create an empty slice slice := []int{} for i := 0; i < 4; i++ { slice = append(slice, i) // append the elements in slice using append function } fmt.Println("The slice created here is:") fmt.Println(slice) // print the slice }
輸出
The slice created here is: [0 1 2 3]
結論
在上面的程式中,我們使用了四個示例來初始化切片。在第一個示例中,我們使用 make 函式建立切片。在第二個示例中,我們使用了簡寫宣告;在第三個示例中,我們使用了 append 函式建立切片;在第四個示例中,我們使用了 for 迴圈在螢幕上列印切片。因此,程式成功執行。