How to Reverse a Slice in Go: Simple Guide and Example
To reverse a slice in Go, you swap elements from the start and end moving towards the center using a loop. Use
for with two indexes, swapping slice[i] and slice[j] until they meet or cross.Syntax
To reverse a slice in Go, use a for loop with two indexes: one starting at the beginning (i) and one at the end (j). Swap the elements at these positions and move i forward and j backward until i is no longer less than j.
go
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 { slice[i], slice[j] = slice[j], slice[i] }
Example
This example shows how to reverse a slice of integers. It prints the original slice, reverses it using the swapping method, and then prints the reversed slice.
go
package main import "fmt" func main() { nums := []int{1, 2, 3, 4, 5} fmt.Println("Original slice:", nums) for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 { nums[i], nums[j] = nums[j], nums[i] } fmt.Println("Reversed slice:", nums) }
Output
Original slice: [1 2 3 4 5]
Reversed slice: [5 4 3 2 1]
Common Pitfalls
One common mistake is trying to reverse the slice by creating a new slice without copying elements properly, which can cause unexpected results or extra memory use. Another is forgetting to update both indexes i and j in the loop, causing an infinite loop or no reversal.
go
package main import "fmt" func main() { nums := []int{1, 2, 3, 4, 5} // Wrong: forgetting to update j for i := 0; i < len(nums)/2; i++ { nums[i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[i] } fmt.Println("Reversed slice:", nums) // Right way: nums = []int{1, 2, 3, 4, 5} for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 { nums[i], nums[j] = nums[j], nums[i] } fmt.Println("Correctly reversed slice:", nums) }
Output
Reversed slice: [5 4 3 2 1]
Correctly reversed slice: [5 4 3 2 1]
Quick Reference
- Use two indexes: start (
i) and end (j). - Swap elements at
iandj. - Move
iforward andjbackward until they meet. - Works for slices of any type.
Key Takeaways
Reverse a slice by swapping elements from start and end moving inward.
Use a for loop with two indexes to swap elements until they meet or cross.
Always update both indexes in the loop to avoid infinite loops.
This method works in-place without extra memory allocation.
You can reverse slices of any data type using this approach.