Golang iterate over slice in reverse? [SOLVED]


Written by - Tuan Nguyen
Reviewed by - Deepak Prasad

In Golang, iterating over a slice is surprisingly straightforward; In this article, we will learn how to iterate over a slice in reverse in Go.

 

Example 1: Using a loop that counts down the index

There isn't a practical operator to solve this. But we can simply use a normal loop that counts down the index and iterate over it in reverse order. Here is an example of how we can do it in Golang:

package main

import "fmt"

func main() {
	intSlice := []int{12, 23, 9, 32, 182}
	// counting down the index
	for i := len(intSlice) - 1; i >= 0; i-- {
		fmt.Println(intSlice[i])
	}
}

Output:

182
32
9
23
12

 

Example 2: Using a loop that handles the index

In this example, we will try to handle the index when iterating the slice so it can print the slice in reverse order:

package main

import "fmt"

func main() {
	intSlice := []int{12, 23, 9, 32, 182}
	sliceLen := len(intSlice)

	for i := range intSlice {
		// handle the index
		reverseIndex := sliceLen - 1 - i
		fmt.Println(intSlice[reverseIndex])
	}
}

Output:

182
32
9
23
12

 

Example 3: Using generic to write a function for multiple data type slices

In this example, we will use the generics to write a function that takes any data types slices as a parameter and print out all the elements in reverse order:

package main

import "fmt"

func reverseIterate[T any](slice []T) {
	for i := len(slice) - 1; i >= 0; i-- {
		fmt.Printf("%v ", slice[i])
	}
}

func main() {
	intSlice := []int{12, 23, 9, 32, 182}
	reverseIterate(intSlice)
	fmt.Println()

	strSlice := []string{"This", "is", "reverse", "iterating", "example"}
	reverseIterate(strSlice)
}

Output:

182 32 9 23 12 
example iterating reverse is This

 

Example 4: Using a channel to reverse the slice

One method to iterate the slice in reverse order is to use a channel to reverse a slice without duplicating it. Let's take a look at the example below to see how we can use a channel to reverse a slice and print it in the reverse order:

package main

import (
	"fmt"
)

func reverseSlice(slice []string) chan string {
	result := make(chan string)
	go func() {
		for i, _ := range slice {
			result <- slice[len(slice)-1-i]
		}
		close(result)
	}()
	return result
}

func main() {
	strSlice := []string{"a", "b", "c", "d"}
	for element := range reverseSlice(strSlice) {
		fmt.Println(element)
	}
	fmt.Println("Original slice:", strSlice)
}

Output:

d
c
b
a
Original slice: [a b c d]

 

Summary

In this article, I already show you some examples of iterating over a slice in reverse order. We can simply use a normal loop that handles the index order. Another way to print the slice in reverse order is to use a channel to sort the slice first and then iterate through it. With the generics, example 3 shows us how to write a function to sort slices of any data type.

 

References

Is there a way to iterate over a slice in reverse in Go?

 

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment