≡ Menu

12 Practical Array Examples in GoLang Go Programming Language

[GoLang Array Examples]To get a good handle on Go programming language, it is essential to understanding arrays and slices.

If you are developer, or sysadmin who is new to Go, it is important to understand the following key differences in how array is handled in Go when compared to other language:

  • You cannot change the size of the array once it is declare.
  • The array size should be specified when you declare an array. To overcome this limitation, you’ll be using slices for most part in GoLang. But, it still sill important to understand how array works, as slices works on top of array.
  • When you assign an array to another array, essentially you are copying all the elements from one to another.
  • The above is important to understand, as when you are passing an array as a parameter in an function, the function will really get a copy of the array and will work on it. It is not a pointer that we are passing. It is copy of the whole array.

This tutorial explains the following basics of array handling in Go, with a full working example along with the output that is provided at the end of this tutorial.

  1. Declare an Array Variable with a Specific Size
  2. Assign a Value to a Specific Element in an Array
  3. Access a particular Element in an Array
  4. Display All or Specific Elements from an Array
  5. Initialize and Assign values to Array at the Same time
  6. Initialize an Array using Multi-Line Syntax
  7. Identify Length of an Array – How many Elements are there?
  8. Default value of an Array Element
  9. Loop through Array Elements using For and Range
  10. Loop through an Array and get only the Values (Ignore Array Index)
  11. Initialize an Int Array elements with Number Sequence
  12. Define and Intialize Multi-Dimentional Arrays
  13. Full Working GoLang Code with All Array Examples

In an upcoming article, we’ll cover slices in GoLang with examples.

1. Declare an Array Variable with a Specific Size

var distros [5]string

var ids [5]int

In the above:

  • var – keyword
  • distros, ids – the name of the variable
  • 5 – This is the array length. You have to specify the length of the array when declaring an array. Once you specify a size of the array, you cannot resize.
  • string, int – The type of the array. In this example, distros is a string array with size of 5, and ids is an int array with size of 5.

2. Assign a Value to a Specific Element in an Array

distros[0] = "Ubuntu"
distros[1] = "CentOS"
distros[2] = "RedHat"
distros[3] = "Debian"
distros[4] = "OpenBSD"

ids[0] = 1
ids[1] = 2
ids[2] = 3
ids[3] = 4
ids[4] = 5

Notes:

  • As you see above, the index reference that you’ll use for the 1st element of the array is 0 (not 1).
  • distros[0] refers to the 1st element in the distros array
  • ids[4] refers to the 5th element in the ids array (which is also the last element of ids array in this example)

If you try to assign a value at a location in an array that is beyond the size of the array, then you’ll get an error message.

For example, if you do the following, it will fail, because our distros array has only 5 elements, and we are trying to assign a value to the 6th element, which doesn’t exist in our array. You cannot add a new element to an existing array.

distros[5] = "Solaris"

Error message:

./array.go:11:10: invalid array index 5 (out of bounds for 5-element array)

3. Access a particular Element in an Array

mydistro := distros[1]

myid := ids[3]

Notes:

  • We are assigning the value of 1st element of distros array to mydistro variable
  • Assigning 3rd element of the ids array to myid variable
  • := will declare and initialize the variable at the same time
  • Also, for := you don’t need to specify the type of the mydistro or myid variable
  • := know will decide the type of the variable based on the value that is getting assigned.
  • So, mydistro will become string variable, and myid will become int variable automatically

4. Display All or Specific Elements from an Array

fmt.Println(distros)
fmt.Println(ids)

fmt.Println("distros[2] = ", distros[2])
fmt.Println("ids[2] = ", ids[2])

To display a specific array element or all the elements in an array, use fmt.Println as show above.

Make sure “fmt” package is imported on the top using import command

When you print the whole array, in the output, it will display all the elements inside square parentheses as shown below.

[1 2 3 4 5]
[Ubuntu CentOS RedHat Debian OpenBSD]

5. Initialize and Assign values to Array at the Same time

Instead of declaring an array variable first, and then initializing the values separately, you can combine them together.

The following will both declare and initialize an array with the given values at the same time.

os := [3]string{"Linux", "Mac", "Windows"}

fibonacci := [6]int{1, 1, 2, 3, 5, 8}

6. Initialize an Array using Multi-Line Syntax

For better clarify and readability, you can also use multi-line syntax while initializing and assigning values to an array as shown below.

temperature := [3]float64{
     98.5,
     65.5,
     83.2,
}

But, keep in mind that in the multi-line syntax, you have to specify a comma after the last element. As you see above, there is a comma after 83.2

The advantage of this syntax is that you can comment out a particular value in an array without having to worry about removing the comma as shown below. In the following example, we have commented out the last value in the array. But, we didn’t have to worry about removing the comma after Alicia.

names := [3]string{
     "John",
     "Jason",
     "Alica",
     // "Rita",
}

7. Identify Length of an Array – How many Elements are there?

len function will return the total number of elements in the given array. You can assign the value of the len function to another variable also.

arraySize := len(distros)

fmt.Println("Number of distros = ", len(distros))
fmt.Println("Number of ids = ", len(ids))

Output:

Number of distros =  5
Number of ids =  5

8. Default value of an Array Element

In an integer array, if you don’t assign value to an array, and try to print it, you’ll see 0 as values for the elements that you didn’t assign a value to. By default, integer arrays are initialized with 0 as values.

In the following example, we defined empIds array with 5 elements, but assigned values only to the first three elements.

empIds := [5]int{101, 102, 103}

fmt.Println("empIds = ",empIds)

As you see fro the following output, the last two elements are assigned value of 0 automatically.

empIds =  [101 102 103 0 0]

For string arrays, if you don’t assign a value, it will just have empty value We just assigned two elements, and left the last three elements empty.

empNames := [5]string{"John","Jason"}

fmt.Println("empNames = ",empNames)

Output:

empNames =  [John Jason   ]

9. Loop through Array Elements using For and Range

Using for and range commands you can loop through all the elements in a given array

for index, value := range distros {
  fmt.Println(index, " = ", value)
}

In the above:

  • range distros – range is a go command which will return the index number and the value of an array element.
  • You can assign the output of the range command to a for loop and loop through all the elements
  • for i, value – Here specify two variable to the for command. The variable name can be anything. It just happened for clarity we are using index and value as the variable name here.

10. Loop through an Array and get only the Values (Ignore Array Index)

If you just want to use the array element and not the index, then specifying the index variable as shown below will give error message.

In this example, we just want to loop through all the values in the ids array and total them. So, we really don’t care about the index variable here.

total := 0
for index, value := range ids {
  total = total + value
}
fmt.Println("total of all ids = ", total)

The above will throw the following error:

./array.go:54:7: index declared and not used

In this case, just replace the index variable in the for loop with _ underscore as shown below.

for _, value := range ids {
  total = total + value
}

An _ underscore indicates Go language that you take the value of a particular variable (in this case index) and just ignore it.

11. Initialize an Int Array elements with Number Sequence

The following example shows how you can assign sequential values to an init array using for loop.

var sequence [10]int
counter := 10
for index, _ := range sequence {
  sequence[index] = counter
  counter = counter + 5
}
fmt.Println()
fmt.Println("sequence = ",sequence)

In the above, we are using for and range to loop through the array elements and assign an value. Since we just care about the index and not the current value of the array element, we are using _ underscore for the value in the for loop as shown above.

In this example, the sequence starts with 10 in the increment of 5. So, the first value of the array will be 10 and increment to 5 from thereafter.

12. Define and Intialize Multi-Dimentional Arrays

Go doesn’t have the concept of multi-dimensional array. But, you can do arrays-of-arrays, which can be treated and used as a multi-dimensional array as shown below.

count := 1
var multi [4][2]int
 for i := 0; i < 4; i++ {
     for j := 0; j < 2; j++ {
         multi[i][j] = count
         count++
     }
 }
 fmt.Println("Array 4 x 2 : ", multi)

In the above example, we are creating an init array of dimension 4 x 2 (4 rows and 2 columns) and assigning values to the individual elements in the increments of 1 starting from value 1.

Go Code with All Array Examples

For your reference, the following working go code contains all the above examples in one program.

package main

import "fmt"

func array() {

  // String Array
  fmt.Println("1. String Array : ")

  var distros [5]string
  distros[0] = "Ubuntu"
  distros[1] = "CentOS"
  distros[2] = "RedHat"
  distros[3] = "Debian"
  distros[4] = "OpenBSD"

  mydistro := distros[1]
  fmt.Println("mydistro = ", mydistro)
  fmt.Println("distros[2] = ", distros[2])
  fmt.Println("distros = ", distros)
  fmt.Println("Number of distros = ", len(distros))

  // Integer Array (Numbers)
  fmt.Println()
  fmt.Println("2. Integer Array : ")

  var ids [5]int
  ids[0] = 1
  ids[1] = 2
  ids[2] = 3
  ids[3] = 4
  ids[4] = 5

  myid := ids[3]
  fmt.Println("myid = ", myid)
  fmt.Println("ids[2] = ", ids[2])
  fmt.Println("ids = ", ids)
  fmt.Println("Number of ids = ", len(ids))

  // Declare and Initialize Array at the same time
  fmt.Println()
  fmt.Println("3. Declare and Initialize Array at the same time : ")

  os := [3]string{"Linux", "Mac", "Windows"}
  fmt.Println("os = ",os)
  fmt.Println("Number of os = ", len(os))

  fibonacci := [6]int{1, 1, 2, 3, 5, 8}
  fmt.Println("fibonacci = ",fibonacci)

  // Multi-line Array Initialization Syntax
  fmt.Println()
  fmt.Println("4. Multi-line Array Initialization Syntax : ")

  temperature := [3]float64{
       98.5,
       65.5,
       83.2,
  }
  fmt.Println("temperature = ", temperature)

  names := [3]string{
       "John",
       "Jason",
       "Alica",
       // "Rita",
  }
  fmt.Println("names = ", names)

  // Default Values in an Array
  fmt.Println()
  fmt.Println("5. Default Values in an Array : ")

  empIds := [5]int{101, 102, 103}
  fmt.Println("empIds = ",empIds)

  empNames := [5]string{"John","Jason"}
  fmt.Println("empNames = ",empNames)

  // Loop through Array using For and Range
  fmt.Println()
  fmt.Println("6. Loop through Array using For and Range : ")

  for index, value := range distros {
    fmt.Println(index, " = ", value)
  }

  // Loop through Array using For and Range (Ignore Index)
  fmt.Println()
  fmt.Println("7. Loop through Array using For and Range (Ignore Index) : ")

  total := 0
  for _, value := range ids {
    total = total + value
  }
  fmt.Println("total of all ids = ", total)

  // Initialize an integer array with sequence
  fmt.Println()
  fmt.Println("8. Initialize an integer array with sequence : ")
  var sequence [10]int
  counter := 10
  for index, _ := range sequence {
    sequence[index] = counter
    counter = counter + 5
  }
  fmt.Println("sequence = ",sequence)

  // Multi dimensional array
  fmt.Println()
  fmt.Println("9. Multi dimensional array : ")

  count := 1
  var multi [4][2]int
   for i := 0; i < 4; i++ {
       for j := 0; j < 2; j++ {
           multi[i][j] = count
           count++
       }
   }
   fmt.Println("Array 4 x 2 : ", multi)

}

Full output for the above example code:

1. String Array :
mydistro =  CentOS
distros[2] =  RedHat
distros =  [Ubuntu CentOS RedHat Debian OpenBSD]
Number of distros =  5

2. Integer Array :
myid =  4
ids[2] =  3
ids =  [1 2 3 4 5]
Number of ids =  5

3. Declare and Initialize Array at the same time :
os =  [Linux Mac Windows]
Number of os =  3
fibonacci =  [1 1 2 3 5 8]

4. Multi-line Array Initialization Syntax :
temperature =  [98.5 65.5 83.2]
names =  [John Jason Alica]

5. Default Values in an Array :
empIds =  [101 102 103 0 0]
empNames =  [John Jason   ]

6. Loop through Array using For and Range :
0  =  Ubuntu
1  =  CentOS
2  =  RedHat
3  =  Debian
4  =  OpenBSD

7. Loop through Array using For and Range (Ignore Index) :
total of all ids =  15

8. Initialize an integer array with sequence :
sequence =  [10 15 20 25 30 35 40 45 50 55]

9. Multi dimensional array :
Array 4 x 2 :  [[1 2] [3 4] [5 6] [7 8]]
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Yordan Sikkreth March 6, 2019, 3:27 am

    … Oh, my God! This thing kind of looks like Pascal, if anybody still uses that thing.

    So! Now you are producing articles as …… okay, after long time,

    yeah, by the way:
    “Copyright © 2008–2018 Ramesh Natarajan. All rights reserved | Terms of Service”

    update now it is 2019…. and counting, ….

  • Anonymous March 20, 2019, 2:21 am

    So glad to see new content! Super glad you’re back. I’m a Python user and have no Go experience, but it’s great to see what Go has to offer. Thanks for all you do. Tremendous work as always, and best of luck in 2019!