Golang Array Quick Notes

Md. Tawsif Ul Karim
2 min readFeb 5, 2021

An array is a numbered sequence of elements of a specific length. If you need something which can grow and shrink then use slice instead. If you have come from a PHP background, then u can think of it as an indexed array [1, 2, 3] but the type is strict.

//Declaration
var a [5]int
  • If the element’s value is not assigned then zero value/default value of the type is used. For int type the zero value is 0. So variable a contains 5 zero in this case
e := [3]bool{true, 1 == 1}
//3rd element is not assigned. So its a zero value(defaults to false for boolean)
fmt.Println(e) //output: true, true, false
  • Array length declared inside the square bracket [] is determined during compile time. So you cannot declare like this:
var a[x]int //this is not possible where x is a variable that might   chnage at any time
  • arrays are reference type, meaning you can directly change a value like this:
a[1] = 100
  • Shorthand Declaration:
a := [4]int{1, 2, 3, 4} //shorthand declaration
fmt.Println(a[0]) //output: 1
  • Declaring without specifying the size
abc := [...]int{1, 4, 5, 1, 4, 6}

The three dots … tells the compiler that figure out yourselves the length of this array.
Note: if you omit the three dot then it will turn into a slice which is just like an array but can grow and shrink

  • accessing part of array
z := [5]int{61, 62, 33, 14, 45}//   index: 0   1   2   3   4

Here is the syntax to access elements: (VERY IMPORTANT)

 z[startIndexIncluding : uptoNotIncludingIndex]
  • Some Examples
fmt.Println(z[2:4]) //output: [33, 14]//if we want to access value from index 0 to index 3 thenfmt.Println(z[:3])  //output: 61 62 33if we want to access from index 1 to end thenfmt.Println(z[1:])  //output: 62 33 14 45
  • to find the length
length := len(z)

--

--

Md. Tawsif Ul Karim
0 Followers

Ordinary boy with some extra ordinary dreams. Currently suffering from awesomenia