How to iterate over an array using the for loop in Go?

I have an array of strings and I want to iterate and print its elements using the for loop in Golang.

  1. Accepted Answer

Accepted Answer

Using the range clause

You can use the range keyword with the for loop to iterate over your array and print its elements. When you apply range to an array, it returns the index as an integer and the item. Here’s an example:

func printArray() {
	alphabets := []string{"A", "B", "C", "D", "E"}

	for index, letter := range alphabets {
		fmt.Println(index, " => ", letter)
	}
}

This outputs:

0  =>  A
1  =>  B
2  =>  C
3  =>  D
4  =>  E

Additionally, if you want to print up to X elements, e.g. let’s say you have a very large array and you want to print first 5 elements only, you can use slices with the range function. For example, to print the first 3 elements of an array only, you could:

func printArray() {
	alphabets := []string{"A", "B", "C", "D", "E"}

	for index, letter := range alphabets[:3] {
		fmt.Println(index, " => ", letter)
	}
}

This will output:

0  =>  A
1  =>  B
2  =>  C

Additionally, you could also use the vanilla C-style for loop to iterate over an array. Use the range method in practice as it is more idiomatic and go-like.

func printArrayUsingCLikeFor() {
	alphabets := []string{"A", "B", "C", "D", "E"}

	for i := 0; i < len(alphabets); i++ {
		fmt.Println(i, " => ", alphabets[i])
	}
}

See you next time.

Speak Your Mind