如何在Golang中将数组复制到另一个数组()

数组
Golang或Go编程语言中的语言与其他编程语言非常相似。在程序中, 有时我们需要存储一组相同类型的数据, 例如学生评分列表。这种类型的集合使用数组存储在程序中。数组是固定长度的序列, 用于将同类元素存储在内存中。 Golang没有提供将一个数组复制到另一个数组的特定内置函数。但是我们可以通过简单地通过值或引用将数组分配给新变量来创建数组的副本。
如果我们通过值创建数组的副本并在原始数组的值中进行了一些更改, 则它不会反映在该数组的副本中。而且, 如果我们通过引用创建数组的副本并对原始数组的值进行了一些更改, 那么它将反映在该数组的副本中。如以下示例所示:
语法如下:

// creating a copy of an array by valuearr := arr1// Creating a copy of an array by referencearr := & arr1

让我们借助示例来讨论这个概念:
范例1:
// Go program to illustrate how // to copy an array by value package mainimport "fmt"func main() {// Creating and initializing an array // Using shorthand declaration my_arr1 := [5]string{ "Scala" , "Perl" , "Java" , "Python" , "Go" }// Copying the array into new variable // Here, the elements are passed by value my_arr2 := my_arr1fmt.Println( "Array_1: " , my_arr1) fmt.Println( "Array_2:" , my_arr2)my_arr1[0] = "C++"// Here, when we copy an array // into another array by value // then the changes made in original // array do not reflect in the // copy of that array fmt.Println( "\nArray_1: " , my_arr1) fmt.Println( "Array_2: " , my_arr2) }

输出如下:
Array_1:[Scala Perl Java Python Go]Array_2: [Scala Perl Java Python Go]Array_1:[C++ Perl Java Python Go]Array_2:[Scala Perl Java Python Go]

范例2:
// Go program to illustrate how to // copy an array by reference package mainimport "fmt"func main() {// Creating and initializing an array // Using shorthand declaration my_arr1 := [6] int {12, 456, 67, 65, 34, 34}// Copying the array into new variable // Here, the elements are passed by reference my_arr2 := & my_arr1fmt.Println( "Array_1: " , my_arr1) fmt.Println( "Array_2:" , *my_arr2)my_arr1[5] = 1000000// Here, when we copy an array // into another array by reference // then the changes made in original // array will reflect in the // copy of that array fmt.Println( "\nArray_1: " , my_arr1) fmt.Println( "Array_2:" , *my_arr2) }

【如何在Golang中将数组复制到另一个数组()】输出如下:
Array_1:[12 456 67 65 34 34]Array_2: [12 456 67 65 34 34]Array_1:[12 456 67 65 34 1000000]Array_2: [12 456 67 65 34 1000000]

    推荐阅读