Slices Reverse And Backward Walk From The End

Flip order in place with slices.Reverse and walk a slice from its last index with slices.Backward, which yields index and value together.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	queue := []string{"a", "b", "c", "d"}

	// Reverse:原地反转,不分配新切片
	slices.Reverse(queue)
	fmt.Println("reversed:", queue)

	// Backward:从尾到头的迭代器,同时给出下标
	for index, value := range slices.Backward(queue) {
		fmt.Printf("index %d: %s
", index, value)
	}

	// 配合 slices.Clone:反转副本而不动原切片
	fresh := []int{1, 2, 3}
	twin := slices.Clone(fresh)
	slices.Reverse(twin)
	fmt.Println("original:", fresh, "twin:", twin)
}

The mechanics

Slices Reverse And Backward Walk From The End is built around the function main.

Repetition is confined to for index, value := range slices.Backward(queue) — the rest of the file is straight-line.

Applying it

The demo output is labeled (reversed:, original:), so the output doubles as a step-by-step trace of what the file did.

Statements that matter

for index, value := range slices.Backward(queue) {
	fmt.Printf("index %d: %s
", index, value)
}

Interactive Tools for This Topic

FAQ

What does Slices Reverse And Backward Walk From The End print when run?
Running the file directly is enough — expect labeled output lines such as `reversed:`, `original:`.