Skip to content

Commit 1c59000

Browse files
adonovaneric
authored andcommitted
slices: add in-place Reverse function
Fixes golang#58565 Change-Id: I583f8380c12386178fb18e553322bbb019d9fae0 Reviewed-on: https://go-review.googlesource.com/c/go/+/468855 Run-TryBot: Alan Donovan <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Shay Nehmad <[email protected]>
1 parent e19d9ef commit 1c59000

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

api/next/58565.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg slices, func Reverse[$0 interface{}]([]$0) #58565

src/slices/slices.go

+7
Original file line numberDiff line numberDiff line change
@@ -445,3 +445,10 @@ func startIdx[S ~[]E, E any](haystack, needle S) int {
445445
// TODO: what if the overlap is by a non-integral number of Es?
446446
panic("needle not found")
447447
}
448+
449+
// Reverse reverses the elements of the slice in place.
450+
func Reverse[E any](s []E) {
451+
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
452+
s[i], s[j] = s[j], s[i]
453+
}
454+
}

src/slices/slices_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,34 @@ func TestClip(t *testing.T) {
623623
}
624624
}
625625

626+
func TestReverse(t *testing.T) {
627+
even := []int{3, 1, 4, 1, 5, 9} // len = 6
628+
Reverse(even)
629+
if want := []int{9, 5, 1, 4, 1, 3}; !Equal(even, want) {
630+
t.Errorf("Reverse(even) = %v, want %v", even, want)
631+
}
632+
633+
odd := []int{3, 1, 4, 1, 5, 9, 2} // len = 7
634+
Reverse(odd)
635+
if want := []int{2, 9, 5, 1, 4, 1, 3}; !Equal(odd, want) {
636+
t.Errorf("Reverse(odd) = %v, want %v", odd, want)
637+
}
638+
639+
words := strings.Fields("one two three")
640+
Reverse(words)
641+
if want := strings.Fields("three two one"); !Equal(words, want) {
642+
t.Errorf("Reverse(words) = %v, want %v", words, want)
643+
}
644+
645+
singleton := []string{"one"}
646+
Reverse(singleton)
647+
if want := []string{"one"}; !Equal(singleton, want) {
648+
t.Errorf("Reverse(singeleton) = %v, want %v", singleton, want)
649+
}
650+
651+
Reverse[string](nil)
652+
}
653+
626654
// naiveReplace is a baseline implementation to the Replace function.
627655
func naiveReplace[S ~[]E, E any](s S, i, j int, v ...E) S {
628656
s = Delete(s, i, j)

0 commit comments

Comments
 (0)