Golang Arrays - Declare, Initialize, Access

Golang Arrays ? Declare, Initialize, Access

In Golang, Array is a collection of elements of the same datatype.

Golang array is of fixed size. The size mentioned during the declaration of inferred during initialization is the size of the array.

The array is sequential which means that the elements of the array can be access sequentially.

Genarally in programming, an Array is used to store similar kind of values or objects where the sequence of elements matters.

For example, first 5 prime numbers [2, 3, 5, 7, 11] could be declared as an array. Here the elements belong to a same type, integer. Also the sequence matters: first prime number is 2, fourth prime number is 7, and like.

Golang Array

In this tutorial, we will learn how to declare an array in Golang, initialize the array and access the elements of the array.

Golang Array Declaration

To declare an array in Golang, use the following syntax.

var array_name [size] datatype

where var is the keyword. The array we are declaring is treated as a variable. array_name is the name that you give to the array, so that you can access its elements in the subsequent program statements. size is the number of elements that you would like to store in the array. datatype is the only data type of elements that is allowed for this array.

Following is an example, where we declare an array with primes as array_name, 5 as size and int as datatype.

package main func main() {

var primes [5] int }

If you run this program, you will get a warning saying that primes declared and not used . That is just fine what we have done. We have just declared the array. We will soon initialize the array.

Golang Golang Tutorial Run Golang Program Golang If Else Golang Switch Golang For Loop Golang Comments Golang Functions Golang Array Golang Slice Golang Struct Golang Class Golang Range Golang Map Golang Goroutine Golang Channel

Golang String Operations Golang String Length Golang String Concatenation Golang Split String Golang String - Get Index of Substr Golang String to Uppercase Golang String to Lowercase Golang Convert String to Integer

Golang Convert String to Integer

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download