×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Language - Copying Arrays

In Go, arrays are fixed-size collections of elements of the same type. When copying an array, you can use different methods, such as assignment, loops, or the copy() function.

Copying Arrays Using Assignment

In Go, assigning one array to another creates a copy rather than a reference. Below is an example:

package main
import "fmt"

func main() {
    arr1 := [3]int{10, 20, 30} // Original array
    arr2 := arr1 // Copying array using assignment

    arr2[0] = 100 // Modifying arr2 does not affect arr1

    fmt.Println("Original Array:", arr1)
    fmt.Println("Copied Array:", arr2)
}

When executed, this program outputs:

Original Array: [10 20 30]
Copied Array: [100 20 30]
    

Copying Arrays Using a Loop

Another method to copy an array is using a loop to copy each element individually:

package main
import "fmt"

func main() {
    arr1 := [3]int{5, 10, 15}
    var arr2 [3]int // Declare an empty array

    for i := 0; i < len(arr1); i++ {
        arr2[i] = arr1[i]
    }

    fmt.Println("Original Array:", arr1)
    fmt.Println("Copied Array:", arr2)
}

When executed, this program outputs:

Original Array: [5 10 15]
Copied Array: [5 10 15]
    

Copying Arrays Using the copy() Function

The copy() function in Go is primarily used for slices, but it can also be applied to arrays if converted to slices.

package main
import "fmt"

func main() {
    arr1 := [4]int{1, 2, 3, 4}
    var arr2 [4]int

    copy(arr2[:], arr1[:]) // Using copy function with slices

    fmt.Println("Original Array:", arr1)
    fmt.Println("Copied Array:", arr2)
}

When executed, this program outputs:

Original Array: [1 2 3 4]
Copied Array: [1 2 3 4]
    
Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.