Golang arrays guide

Lets learn Golang arrays, how to declare them and how to use them.

Page content

After you finish this article you will start playing with arrays like pawns

Intro

Arrays are one of the most famous data structures in different programming languages. Different data types can be handled as elements in arrays such as int, float23, double and others The following code snippet shows the initialiazation of an array (array.go):

var arr = [4]int{1,4,5,6}

An Array has a size or a length which can found by

len(arr)

Array elements

To access the array elements there is two different ways:

  • We loop through the array, by figuring out its length
var i int
for i =0; i<len(arr); i++{
    fmt.Println("priting elements ", arr(i))
}
  • We range through the elements and assign, index value to the array
for i,v := range arr{
    fmt.Println("priting elements ",i, v)
}

Ignoring the index

If we need to ignore the index we can use the _ blank identifier

for _,v := range arr{
    fmt.Println("priting elements ",i, v)
}

https://go.dev/blog/slices-intro Arrays, slices (and strings): The mechanics of ‘append’ https://stackoverflow.com/questions/33834742/remove-and-adding-elements-to-array-in-go-lang Append to slice or array of struct page.