Go語言程式:將一個數組的所有元素複製到另一個數組


在本教程中,我們將學習如何編寫一個Go語言程式,將一個數組的所有元素複製到另一個數組。

使用等號運算子複製一個數組的所有元素到另一個數組

現在讓我們來看一個Go語言程式碼,它使用等號運算子將一個數組的所有元素複製到另一個數組。

演算法

步驟1 - 匯入fmt包。

步驟2 - 呼叫main()函式。

步驟3 - 初始化並定義一個字串型別的陣列,並向其中儲存值。

步驟4 - 在螢幕上列印此陣列。

步驟5 - 建立一個名為my_arr2的新陣列,並使用等號運算子將第一個陣列的所有內容複製到第二個陣列。

步驟6 - 新建立的陣列包含原始陣列的所有值。我們需要使用fmt.Println()函式在螢幕上列印此陣列。

示例

package main
import "fmt"
func main() {
   my_arr1 := [5]string{"Apple", "Mango", "Banana", "Pineapple", "Tomato"}
   my_arr2 := my_arr1
   fmt.Println("The first array, arr1 is:", my_arr1)
   fmt.Println("The array obtained after copying the contents of arr1:", my_arr2)
}

輸出

The first array, arr1 is: [Apple Mango Banana Pineapple Tomato]
The array obtained after copying the contents of arr1: [Apple Mango Banana Pineapple Tomato]

使用內部函式複製一個數組的元素到另一個數組

現在,讓我們來看另一個將一個數組的內容複製到另一個數組的示例。在這個示例中,我們將使用一個名為copy()的預定義函式來儲存陣列的內容。

語法

func copy(dst, str[] type) int

Go語言中的copy函式用於將一個源陣列的值複製到目標陣列,並返回已複製的元素數量作為結果。它以兩個陣列作為引數。

func make ([] type, size, capacity)

Go語言中的make函式用於建立陣列/對映,它接受要建立的變數的型別、大小和容量作為引數。

演算法

步驟1 - 首先,我們需要匯入fmt包。

步驟2 - 然後我們需要呼叫main()函式。

步驟3 - 初始化一個名為src的整數陣列,並向其中儲存值。在螢幕上列印此陣列。

步驟4 - 現在,使用make()函式建立一個名為dst的新整數陣列。

步驟5 - 透過將dst和src陣列作為引數傳遞給copy函式來呼叫它,並將此函式返回的結果儲存在一個新的變數中。

步驟6 - 使用fmt.Println()函式在螢幕上列印dst陣列以及已複製的元素數量。

示例

package main
import "fmt"
func main() {
   src := []int{1, 2, 3, 4, 5}
   fmt.Printf("The source array is: %v\n", src)
   dst := make([]int, 5)
   numberOfElementsCopied := copy(dst, src)
   fmt.Printf("The array obtained after copying the contents of src array is: %v\n", dst)
   fmt.Printf("Number Of Elements Copied: %d\n", numberOfElementsCopied)
}

輸出

The source array is: [1 2 3 4 5]
The array obtained after copying the contents of src array is: [1 2 3 4 5]
Number Of Elements Copied: 5

使用for迴圈將一個數組的所有元素複製到另一個數組

現在讓我們編寫一個Go語言程式,使用for迴圈將一個數組的內容複製到另一個數組。

語法

func len(v Type) int

len()函式用於獲取變數的長度。它以元素作為引數,並返回其長度。

演算法

步驟1 - 首先,我們需要匯入fmt包。

步驟2 - 然後我們需要呼叫main()函式。

步驟3 - 初始化一個名為src的整數陣列,並向其中儲存值。在螢幕上列印此陣列。

步驟4 - 現在,使用make()函式建立一個名為dst的新整數陣列。

步驟5 - 現在,我們使用for迴圈將一個數組的內容複製到另一個數組。

步驟6 - 使用fmt.Println()函式在螢幕上列印dst陣列以及已複製的元素數量。

示例

package main
import "fmt"
func main() {
   src := []int{1, 2, 3, 4, 5}
   fmt.Printf("The source array is: %v\n", src)
   dst := make([]int, 5)
   for i := 0; i < len(src); i++ {
      dst[i] = src[i]
   }
   fmt.Printf("The array obtained after copying the contents of src array is: %v\n", dst)
   fmt.Printf("Number Of Elements Copied: %d\n", len(dst))
}

輸出

The source array is: [1 2 3 4 5]
The array obtained after copying the contents of src array is: [1 2 3 4 5]
Number Of Elements Copied: 5

結論

我們已經成功編譯並執行了一個Go語言程式,該程式將一個數組的所有元素複製到另一個數組,並附帶示例。

更新於:2023年1月2日

1K+ 閱讀量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.