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 main
import "fmt"
func main() {
arr1 := [3]string{"a", "b", "c"}
arr2 := [3]string{"a", "b", "c"}
arr3 := [3]string{"1", "2", "3"}
fmt.Println(arr1 == arr2)
fmt.Println(arr2 == arr3)
}
Output:
true
false
Comments
Post a Comment