Go Arrays
Go Language - Arrays
There is a data structure provided by go programming which is called as the array, which can store the sequential collection of elements of fixed size and also same data type.
More often an array is said to be a collection of variables of same type.
e.g. if we are declaring like num1, num2, .......num99, instead here we can declare one array variable such as Numbers and represent each elements of the array as the above individual variables.
The index value is used to access specific element of the array.
Declaring Arrays:
In Go programming, the type of element of the array and numberof elements required should be specified by the programmer as follows,
Syntax
Var variable_name [SIZE] variable_type
This type of declaration is called Single dimensional array. The SIZE will take an integer value greater than zero and the variable_type will take data type of Go.
e.g. var balance [10] float32
A balance array is declared which as size 10 and type of float23.
Initializing Arrays :
Array can be initialized in two ways either in a single statement or one by one using index,
Syntax
var balance =[5]float23{100.0, 12.0,35.5,7.0,54.0}
The number elements in the braces should not exit the size of the array.
The following is the example for assigning single element of the array using index,
Syntax
e.g. balance[4]=54.0
The above statement assign value for the 5thelement in the array balance as 54.0, the base index of all the array is start with 0and the total size minus 1 will give the last index.
The representation how the values of elements stored in the memory,
Accessing Array Elements :
The array elements can be accessed using its name followed by array index which is called array indexing,
For Example :
Syntax
float32 salary= balance[9]
The value of the 10thelement of array is assigned to the salary variable.
The following the illustrate for the above concepts of the array,
CODE/PROGRAM/EXAMPLE
package main
import ”fmt”
func main() {
var n [10]int /* n is an array of 10 integers*/
var i,j int
/*initialize elements of array n to 0 */
for i=0; i< 10; i++ {
n[i]= i+100 /* set element at location i to i+ 100 */
}
/* output each array element’s Value */
for j=0; j<10; j++ {
fmt. Println(“Elements[%d]\n”, j, n[j])
}
O/P :
Element[1]=100
Element[2]=101
Element[3]=102
Element[4]=103
Element[5]=104
Element[6]=105
Element[7]=106
Element[8]=107
Element[9]=100
Element[10]=100