How to Reverse a Slice in Go

1. Introduction

Reversing a slice in Go is a common task that may come up in various programming scenarios. Go does not have a built-in function to reverse slices, but it's straightforward to implement such functionality. In this blog post, we will look at a simple and idiomatic way to reverse a slice of any type in Go.

Definition

Reversing a slice means to rearrange its elements so that the first element becomes the last one, the second element becomes the second to last, and so on. This operation is done in-place, modifying the original slice.

2. Program Steps

1. Create and initialize a slice.

2. Reverse the slice in-place by swapping elements from start to end.

3. Print the reversed slice.

3. Code Program

package main

import "fmt"

// reverseSlice reverses the elements of the slice in place
func reverseSlice(s []int) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i] // Swap elements
	}
}

func main() {
	// Step 1: Create and initialize a slice
	numbers := []int{1, 2, 3, 4, 5}
	fmt.Println("Original slice:", numbers)

	// Step 2: Reverse the slice
	reverseSlice(numbers)

	// Step 3: Print the reversed slice
	fmt.Println("Reversed slice:", numbers)
}

Output:

Original slice: [1, 2, 3, 4, 5]
Reversed slice: [5, 4, 3, 2, 1]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package, which is used for input and output operations.

3. reverseSlice is a function that takes a slice of integers s and reverses it. It uses a for loop to swap the first and last elements, then moves towards the center of the slice, stopping when the indices cross.

4. numbers is a slice that is initialized with a sequence of integers to demonstrate the reverse operation.

5. reverseSlice(numbers) is called to reverse the numbers slice.

6. The program prints out the original slice and then the reversed slice.

7. The output displays the numbers slice both before and after the reverse operation, confirming that the slice has been reversed in-place.


Comments