Example for copying an Array by value:
package main
import "fmt"
func main() {
// declare an array
arr1 := [2]int{1, 2}
// copying the array by value
arr2 := arr1
// change the 1st index value of the original declared array, it won't reflect on copyed array
arr1[0] = 10
fmt.Println("Array 1 values :", arr1)
fmt.Println("Array 2 values :", arr2)
}
Output:
Array 1 values : [10 2] Array 2 values : [1 2]
Copying an array by reference:
package main
import "fmt"
func main() {
// declare an array
arr1 := [2]int{1, 2}
// copying the array value by references
arr2 := &arr1
// change the 1st index value of the original declared array, it will reflect on copyed array
// because the arr2 holds value of arr1 address
arr1[0] = 10
fmt.Println("Array 1 values :", arr1)
fmt.Println("Array 2 values :", *arr2)
}
Output:
Array 1 values : [10 2] Array 2 values : [10 2]
Using Copy function:
package main
import "fmt"
func main() {
arr1 := []int{1, 2}
arr2 := make([]int, len(arr1))
copy(arr2, arr1)
fmt.Println("Array 1 values :", arr1)
fmt.Println("Array 2 values :", arr2)
}
Output:
Array 1 values : [1 2] Array 2 values : [1 2]
Using append function:
package main
import "fmt"
func main() {
arr1 := []int{1, 2}
arr2 := make([]int, 0, len(arr1))
arr2 = append(arr2, arr1...)
fmt.Println("Array 1 values :", arr1)
fmt.Println("Array 2 values :", arr2)
}
Output:
Array 1 values : [1 2] Array 2 values : [1 2]
Comments
Post a Comment