Arrays are collection of similar items that share a common name. A common scenario would be a case where you want to store student’s scores in an exam.
Array Declaration
var score 3[int]
The above can be read as – Score is an array of type integer that can hold a maximum of 3 records. Can you guess what should be the output of the below program?
package main import "fmt" func main() { var score [3]int fmt.Println(score) }
Output
[0 0 0]
The output is 0 for each of the 3 elements of the array. What does this output signify?
It simply reflects that once you declare an Array variable it is initialized with 0 value by default. This is in line with Go programming behavior in case of other types like integer, float and string etc.
Assigning to & Retrieving Values from an Array
Declaring: var score [3]int
Assigning: score[0] = 75
Note: Array index starts at 0
Retrieving: fmt.Println(score[0])
A sample code follows:
package main import "fmt" func main() { var score [3]int score[0] = 75 score[1] = 80 score[2] = 67 fmt.Println(score[0]) fmt.Println(score) }
Output
75
[75 80 67]
Slices
Go’s simple Arrays are fixed length, rigid and practically of little use. That’s the reason we’ve Slices in Go that are dynamic in nature and can grow or shrink as per the requirement.
Remember : Unlike Arrays which are Value Types, Slices are Reference Types.
Using Slices
The simplest way to declare a slice is:
var score [ ] int
It’s similar to an Array declaration with a little difference that the length of the array is not defined. As shown in the following example, there’re 3 ways of declaring and using a Slice.
package main import "fmt" func main() { //Varibales can be created and assigned in the follwoing three ways var firstVar []int firstVar = []int{23,21,22} secVar := make([]int, 5) secVar = []int{10,13,11} thirdVar := []int{75,80,67} fmt.Println("First Var=",firstVar) fmt.Println("Second Var=",secVar) fmt.Println("Third Var=",thirdVar) }
Output
First Var= [23 21 22]
Second Var= [10 13 11]
Third Var= [75 80 67]
As seen in the above code sample:
thirdVar := []int{75,80,67}
A simple and short way of declaring & assigning a slice.
package main import "fmt" func main() { score := []int{55,87,11,63,74} reSliced := score[0:2] fmt.Println(reSliced) fmt.Println(score[0:2]) fmt.Println(score[:2])//'start_index' not mentioned, default=0 fmt.Println(score[3:])//'end_index' not mentioned, default= maxlength fmt.Println(score[:]) }
[55 87]
[55 87]
[55 87]
[63 74]
[55 87 11 63 74]
Basant Singh
Latest posts by Basant Singh (see all)
- Go Maps Introduction for Beginners - May 20, 2015
- Go Programming – Arrays and Slices - May 11, 2015
- Golang Switch Case with Sample Code - May 1, 2015