Skip to main content

Posts

Showing posts with the label Arrays in golang

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

Go Arrays with Examples

Arrays: Arrays is used to store multiple values of same types in a single variable. We can create an array with two different ways. Using var keyword      var arr [3] int Using Shortcut variable declaration     arr := [3] int {"a","b","c"} Example: package main import "fmt" func main() { var arr1 = [3]string{"a", "b", "c"} // shothand declaration arr2 := [3]string{"1", "2", "3"} // if we use ellipsis, length of the array is determined by the initialized elements like arr := []string{"1","2"} var arr3 = [...]string{"hello"} fmt.Println("Array 1 length:", len(arr1)) fmt.Println("Array 2 length:", len(arr2)) fmt.Println("Array 3 length:", len(arr3)) } Output: Array 1 length: 3 Array 2 length: 3 Array 3 length: 1 Comparing Two Arrays Example: We are able to compare two arrays using (==) operator. package...