Looping Over Slices In GoLang

Looping Over Slices In GoLang

Learn How To Loop Over Slices in GoLang

In this short tutorial, we'll learn how to loop overs slices in Go.

Create a Slice of Integers

This code example creates a slice of integers:

	// Create a slice of integers.
	numbers := []int{100, 90, 80, 90, 70, 60, 50, 40, 30, 20, 10}

Looping With Range

This code example loops over the integers in the slice and prints out the index and the value:

	// Loop over a slice of integers.
	// Print the index and the value at the index of the slice.
	for index, number := range numbers {
		fmt.Printf("Index: %d | Value: %d\n", index, number)
	}

Looping With Range (Without Index)

This code example loops over the integers in the slice and prints out the value:

	// Loop over a slice of integers.
	// Print the values in the slice.
	for _, number := range numbers {
		fmt.Printf("Value: %d\n", number)
	}

Looping With The Standard For Loop

This code example loops over the integers in the slice and prints out the value:

    // Loop over the slice of integers using the standard for loop.
	for i := 0; i < len(numbers); i++ {
		fmt.Printf("Value: %d\n", numbers[i])
	}

Did you like it? Why don't you try also...

How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang