W3Basic Logo

Go Array

Suppose that you want to write an average function that takes as arguments some floating-point numbers and returns their average. Without variadic functions (which are the topic of the next chapter) and arrays, you would have to write a function for each possible number of arguments.

package main

import "fmt"

func average2(x, y float64) float64 {
	return (x + y) / 2
}

func average3(x, y, z float64) float64 {
	return (x + y + z) / 3
}

func average4(x, y, z, w float64) float64 {
	return (x + y + z + w) / 4
}

func main() {
	fmt.Println(average2(1, 2))
	fmt.Println(average3(1, 2, 3))
	fmt.Println(average4(1, 2, 3, 4))
}

But this is not very elegant, nor practical. What if you want to average 5 numbers? 10 numbers? 100 numbers?


What is an Array?

An array is a new type of variable/constant that can store a fixed number of values of the same type.

Creating an Array in Go

The Syntax to create an array in Go is:

var arr_name = [size]datatype{elements of array}

Let us take a simple example to demonstrate arrays.

package main

import "fmt"

func main() {
	var x [5]int = [5]int{1, 2, 3, 4, 5}
	fmt.Println(x)

}

Output

[1 2 3 4 5]

The type of the array is [5]int, which means that it is an array of 5 integers. The type of the array is part of its type, so [5]int and [10]int are two different types.

When you are giving the values of an array, you can omit the type of the array if you want. The compiler will infer it from the values.

var x = []int{1, 2, 3, 4, 5}

We can also use the shorthand notation to declare an array in Go.

x := [5]int{1, 2, 3, 4, 5}

Initialize an Array in Go

We can also intialize array elements using their index number as shown below.

package main

import "fmt"

func main() {
	var languages [3]string
	languages[0] = "Go"
	languages[1] = "Python"
	languages[2] = "Java"
	fmt.Println(languages)
}

Output

[Go Python Java]

Getting a specific element of an array

You can get a specific element of an array by using the index of the element in square brackets.

package main

import "fmt"

func main() {
	var x = []int{1, 2, 3, 4, 5}

	fmt.Println(x[0]) // first element
	fmt.Println(x[1]) // second element

}

Output

1
2

In Go, the first element of an array has index 0, not 1.

Modifying the Array elements in Go

We can modify the array elements by assigning the new value to the specific index of an array. For Example:

package main

import "fmt"

func main() {
	x := [5]int{1, 2, 3, 4, 5}
	fmt.Println("Before Modification:", x)
	x[0] = 10
	x[2] = 30
	fmt.Println("After Modification:", x)

}

Output

Before Modification: [1 2 3 4 5]
After Modification: [10 2 30 4 5]

We have modified the array and assigned the new values to index 0 and index 2.

FInding the length of an array in Go

We can use a built-in len() function to find the total number of elements present inside an array.

package main

import "fmt"

func main() {
	x := [5]int{1, 2, 3, 4, 5}
	fmt.Println("Length of an array is::", len(x))
}

Output

Length of an array is:: 5

This is very useful in loops when you want to iterate over all the elements of an array.

Looping through an Array

We can loop through each elements of an array using the for loop. In the below example we have created an array of undefined size and using the loop we are iterating and accessing the elements of array and print them.

package main

import "fmt"

func main() {
	languages := [...]string{"Go", "Python", "Java"}

	// using for loop to iterate elements of array
	for i := 0; i < len(languages); i++ {
		fmt.Println(languages[i])
	}

}

Output

Go
Python
Java

Partial Assignment of Array in Go

We can also do partial assignment of array in Go as shown below.

package main

import "fmt"

func main() {
	x := [5]int{1, 2, 3}
	fmt.Println(x)
}

Output

[1 2 3 0 0]

Since we have a fixed size here the elements must match the type and size. Hence Go will initialize the elements that does not have value to 0

A better average function

Now that we have arrays, we can write a better average function that takes an array of floating-point numbers as argument and returns their average.

package main

import "fmt"

func average(x []float64) float64 {
	var sum float64 = 0
	for i := 0; i < len(x); i++ {
		sum += x[i]
	}
	return sum / float64(len(x))
}

func main() {
	var x = []float64{1, 2, 3, 4, 5}
	fmt.Println(average(x))
	var y = []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	fmt.Println(average(y))
}

© 2023 W3Basic. All rights reserved.

Follow Us: