Thursday, 2 May 2019

Go Language: Arrays


Array is a collection that stores elements of same type.

Syntax
arrayame := [size]dataType{}

Example
countries := [5]string{}

Above statement defines an array of strings of size 5. ‘countries’ can able to store 5 strings.

HelloWorld.go
package main

import "fmt"

func main() {
 countries := [5]string{}

 countries[0] = "India"
 countries[1] = "Bangladesh"

 fmt.Println(countries)
}

Output
[India Bangladesh   ]

One problem with mentioning size to the array is, we can’t insert elements > size of the array.


HelloWorld.go
package main

import "fmt"

func main() {
 countries := [5]string{}

 countries[0] = "India"
 countries[1] = "Bangladesh"
 countries[2] = "Canada"
 countries[3] = "Austria"
 countries[4] = "Germany"

 countries[5] = "Sri lanka"

 fmt.Println(countries)
}

As you see above program, I mentioned size of array as 5, but I am trying to insert 6th element into the array.

When you run HelloWorld.go program, you will end up in below error.

$ go run HelloWorld.go
# command-line-arguments
./HelloWorld.go:14:11: invalid array index 5 (out of bounds for 5-element array)

Length of the array
You can use ‘len’ function to get the length of the array.


HelloWorld.go
package main

import "fmt"

func main() {
 countries := [5]string{}

 countries[0] = "India"
 countries[1] = "Bangladesh"

 fmt.Println("Array length : ", len(countries))
}

Output
Array length :  5

Note
Once array is defined, its length is fixed, it can't be resized.



Previous                                                 Next                                                 Home

No comments:

Post a Comment