Skip to main content

Posts

Showing posts with the label Copying an array using golang

Copy function in Golang

How Copy function works ? The built-in copy function copies the source element into the destination element and returns the destination element length.   func Copy( dst , src [] Type) int There are some special case using this function which is we can copy a string into an byte slice variable   func Copy( dst []byte, src string) int Examples: package main import "fmt" func main() { var arr = make([]string, 2) n := copy(arr, []string{"hi", "hello", "welcome", "ll"}) fmt.Println("element length :", n) fmt.Println("values :", arr) } Output: element length : 2 values : [hi hello] Special Case example: package main import "fmt" func main() { var b = make([]byte, 5) // copy from a string to byte slice n := copy(b, "vicky") fmt.Println("element length :", n) fmt.Println("values :", string(b)) } Output: element length : 5 values : vicky

Different methods of copying an array using Golang

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 ...