English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statement

Golang Function & Method

Golang Struct

Golang Slice & Array

Go String(String)

Go Pointer

Go Interface

Go Concurrency

Go Error

Go Miscellaneous

Go Language Array Copy

In the Go programming languageArrayIt is very similar to other programming languages. In a program, sometimes we need to store a set of data of the same type, such as a list of student grades. This type of collection is stored in the program using an array. An array is a fixed-length sequence used to store elements of the same type in memory. Go does not provide a specific built-in function to copy one array to another. However, we can create a copy of the array by simply assigning the array to a new variable by value or by reference.

If we create a copy of the array by value and make some changes to the values in the original array, it will not be reflected in the copy of the array. And if we create a copy of the array by reference and make some changes to the values in the original array, it will be reflected in the copy of the array. As shown in the following example:

Syntax:

//create a copy of the array by value
arr := arr1
//create a copy of the array by reference
arr := &arr1

Example

:1copy array by value

//]string{"Scala", "Perl", "Java", "Python", "Go"}
copy array by reference
package main
import "fmt"
    //func main() {
    //create and initialize an array
    my_arr1 using shorthand declaration5Here, elements are passed by value
    //,
    //:= my_arr
    my_arr2 my_arr1
    fmt.Println("Array_1:1)
    fmt.Println("Array_2:2)
    my_arr1[0] = "C++"
    //Here, when we copy the array
    //put by value into another array
    //then make changes to the original content
    //the array will not be reflected in
    //a copy of the array
    fmt.Println("\nArray_1:1)
    fmt.Println("Array_2:2)
}

Output:

Array_1[Scala Perl Java Python Go]
Array_2[Scala Perl Java Python Go]
Array_1:++ Perl Java Python Go]
Array_2[Scala Perl Java Python Go]

:

//Example
copy array by reference
package main
import "fmt"
    //func main() {
    //create and initialize an array
    my_arr1 using shorthand declaration6:= &[12]int{ 456]int{ 67]int{ 65]int{ 34]int{ 34}
    //,
    //Here, elements are passed by reference
    my_arr2 := &my_arr1
    fmt.Println("Array_1:1)
    fmt.Println("Array_2: *my_arr2)
    my_arr1[5] = 1000000
    //Here, when we copy the array
    //by reference and put into another array
    //then make changes to the original content
    //the original array will be reflected in
    //a copy of the array
    fmt.Println("\nArray_1:1)
    fmt.Println("Array_2: *my_arr2)
}

Output:

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]