From 3ca52f4c319e56986586e3d519924876320b29fb Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Thu, 16 Feb 2023 11:02:12 -0500 Subject: [PATCH] slices: add in-place Reverse function Fixes #58565 Change-Id: I583f8380c12386178fb18e553322bbb019d9fae0 Reviewed-on: https://go-review.googlesource.com/c/go/+/468855 Run-TryBot: Alan Donovan TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: Shay Nehmad --- api/next/58565.txt | 1 + doc/go1.21.html | 10 ++++++++++ src/slices/slices.go | 7 +++++++ src/slices/slices_test.go | 28 ++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 api/next/58565.txt diff --git a/api/next/58565.txt b/api/next/58565.txt new file mode 100644 index 0000000000..88ae7e52b1 --- /dev/null +++ b/api/next/58565.txt @@ -0,0 +1 @@ +pkg slices, func Reverse[$0 interface{}]([]$0) #58565 diff --git a/doc/go1.21.html b/doc/go1.21.html index 3e63016e02..743e2a3e28 100644 --- a/doc/go1.21.html +++ b/doc/go1.21.html @@ -668,6 +668,16 @@ Do not send CLs removing the interior tags from such phrases. +
slices
+
+

+ The new slices package + provides many common operations on slices, using generic + functions that work with slices of any element type. +

+
+
+
sync

diff --git a/src/slices/slices.go b/src/slices/slices.go index 837863bacc..7de00b342f 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -445,3 +445,10 @@ func startIdx[S ~[]E, E any](haystack, needle S) int { // TODO: what if the overlap is by a non-integral number of Es? panic("needle not found") } + +// Reverse reverses the elements of the slice in place. +func Reverse[E any](s []E) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} diff --git a/src/slices/slices_test.go b/src/slices/slices_test.go index 2f3a03bd9f..a99299321f 100644 --- a/src/slices/slices_test.go +++ b/src/slices/slices_test.go @@ -623,6 +623,34 @@ func TestClip(t *testing.T) { } } +func TestReverse(t *testing.T) { + even := []int{3, 1, 4, 1, 5, 9} // len = 6 + Reverse(even) + if want := []int{9, 5, 1, 4, 1, 3}; !Equal(even, want) { + t.Errorf("Reverse(even) = %v, want %v", even, want) + } + + odd := []int{3, 1, 4, 1, 5, 9, 2} // len = 7 + Reverse(odd) + if want := []int{2, 9, 5, 1, 4, 1, 3}; !Equal(odd, want) { + t.Errorf("Reverse(odd) = %v, want %v", odd, want) + } + + words := strings.Fields("one two three") + Reverse(words) + if want := strings.Fields("three two one"); !Equal(words, want) { + t.Errorf("Reverse(words) = %v, want %v", words, want) + } + + singleton := []string{"one"} + Reverse(singleton) + if want := []string{"one"}; !Equal(singleton, want) { + t.Errorf("Reverse(singeleton) = %v, want %v", singleton, want) + } + + Reverse[string](nil) +} + // naiveReplace is a baseline implementation to the Replace function. func naiveReplace[S ~[]E, E any](s S, i, j int, v ...E) S { s = Delete(s, i, j) -- 2.44.0