Go語言程式:將切片轉換為陣列
切片也可以稱為動態陣列,因為它的值是動態的,而普通陣列是靜態的。這使得切片更高效、更快。它們是按引用傳遞而不是按值傳遞。在這裡,我們將學習使用各種示例將切片轉換為陣列的不同技術。
語法
func append(slice, element_1, element_2…, element_N) []T
append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要向其新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。
func copy(dst, str[] type) int
Go語言中的 copy 函式用於將一個源陣列的值複製到目標陣列,並將複製的元素數量作為結果返回。它以兩個陣列作為引數。
演算法
步驟 1 - 建立一個 main 包,並在程式中宣告 fmt(格式化包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。
步驟 2 - 建立一個切片,並使用 append 函式向切片中新增一些值。
步驟 3 - 初始化一個指定大小的陣列,以便可以將值複製到其中。
步驟 4 - 使用 copy 函式將切片的元素複製到陣列中。
步驟 5 - 使用 fmt.Println() 函式在控制檯上列印陣列,其中 ln 表示換行。
示例 1
在這個示例中,我們將學習如何使用內建函式 copy 將切片轉換為陣列。在這裡,我們將把切片元素複製到建立的陣列中。讓我們深入研究程式碼和演算法,看看它是如何完成的。
package main import "fmt" //create main function to execute the program func main() { var slice []int // initialize slice slice = append(slice, 10) //fill the slice using append function slice = append(slice, 20) slice = append(slice, 30) // Convert the slice to an array array := [3]int{} //initialized an empty array copy(array[:], slice) //copy the elements of slice in newly created array fmt.Println("The slice is converted into array and printed as:") fmt.Println(array) // prints the output: [10 20 30] }
輸出
The slice is converted into array and printed as: [10 20 30]
示例 2
在這個示例中,我們將看到如何使用 for 迴圈將切片轉換為陣列。切片的元素將被賦值給陣列。讓我們仔細檢視程式碼,使我們的概念清晰明瞭。
package main import "fmt" //create main function to execute the program func main() { var slice []int // initialize slice slice = append(slice, 10) //fill the slice using append function slice = append(slice, 20) slice = append(slice, 30) // Convert the slice to an array var array [3]int for i, element := range slice { array[i] = element // store slice elements in the newly created array } fmt.Println("The array is printed after conversion from slice:") fmt.Println(array) // prints the output: [1 2 3] }
輸出
The array is printed after conversion from slice: [10 20 30]
結論
在上面的程式中,我們使用了兩個示例將切片轉換為陣列。在第一個示例中,我們使用了 copy 函式來獲得一個數組。在第二個示例中,我們使用了 for 迴圈,並且在上面的示例中使用了兩個內建函式——append 和 copy。Append 用於向切片中新增元素。因此,程式成功執行。
廣告