Skip to content

proposal: Go 2: add Reverse function to new slices package #47988

@DeedleFake

Description

@DeedleFake

I wanted to comment about this in #47203, but it's been locked, unfortunately. I needed a reverse function for something so I did a manual loop with the intention of replacing it with a call to slices.Reverse() when Go 1.18 comes out, but to my surprise it doesn't seem to have even been proposed. The only equivalent in the standard library that I saw was sort.Reverse(), but that's really inefficient, and a lot more complicated to use, than just a simple reverse.

The proposal's very simple:

package slices

func Reverse[T any](s []T) {
  for i := 0; i < len(s) / 2; i++ {
    r := len(s) - i - 1
    s[i], s[r] = s[r], s[i]
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions