Skip to content

proposal: slices: add Swap and Swapper functions #63169

@mdempsky

Description

@mdempsky

I propose adding to package slices (or package sort):

// Swap swaps s[i] and s[j].
func Swap[S ~[]E, E any](s S, i, j int) { s[i], s[j] = s[j], s[i] }

// Swapper returns a function that swaps s[i] and s[j].
func Swapper[S ~[]E, E any](s S) func(i, j int) { return func(i, j int) { Swap(s, i, j) } }

This is a common operation when implementing sort.Interface (e.g., appears 164 times within $GOROOT). It's not hard to write out by hand, but it's tedious writing s 4 times when it's a long expression, or making sure to get the i/j/j/i ordering right.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions