Skip to content
Related Articles

Related Articles

Improve Article
Copy an Array by Value and Reference into Another Array in Golang
  • Last Updated : 08 Jun, 2020

Array in Golang is a numbered sequence of elements of the same type. The size of the array is fixed. We can access the elements by their index. You can declare an array of size n and type T specifying this way mentioned below.

var array[n]T 

Go doesn’t have an inbuilt function to copy an array to another array. There are two ways of copying an array to another array:

  • By Value
  • By Reference

1. Copying By Value: If we copy an array by value and later changes are made in values of original array, the same changes won’t be reflected in the copy of the original array.

2. Copying By Reference: If we copy an array by reference and later make any changes in the original array, then they will reflect in the copy of the original array created.

Example:




// Golang program to copy an array by value
// and reference into another array
package main
  
import "fmt"
  
func main() {
  
    // original string
    strArray := [3]string{"Apple", "Mango", "Guava"}
  
    // data is passed by value
    Arraybyval := strArray
  
    // data is passed by reference
    Arraybyref := &strArray
  
    fmt.Printf("strArray: %v\n", strArray)
    fmt.Printf("Arraybyval : %v\n", Arraybyval)
    fmt.Printf("*Arraybyref : %v\n", *Arraybyref)
  
    strArray[0] = "Watermelon"
  
    fmt.Printf("After making changes")
  
    fmt.Printf("strArray: %v\n", strArray)
    fmt.Printf("Arraybyval: %v\n", Arraybyval)
    fmt.Printf("*Arraybyref: %v\n", *Arraybyref)
}

Output:

strArray: [Apple Mango Guava]
Arraybyval : [Apple Mango Guava]
*Arraybyref : [Apple Mango Guava]
After making changesstrArray: [Watermelon Mango Guava]
Arraybyval: [Apple Mango Guava]
*Arraybyref: [Watermelon Mango Guava]
My Personal Notes arrow_drop_up
Recommended Articles
Page :