Kevin Amiranoff
Kevin Amiranoff

Reputation: 14543

How to sort a slice in go without mutating the original slice

In Golang, I am trying to sort a slice without mutating the original value

func main() {
    originalArray := []int{4, 2, 1, 1, 2}
    newArray := originalArray
    sort.Ints(newArray)

    fmt.Printf("%v", originalArray) // prints [1 1 2 2 4]
}

How can I sort a slice in golang without mutating the original value?

Upvotes: 4

Views: 4486

Answers (2)

CAFxX
CAFxX

Reputation: 30351

The general way is:

s2 := slices.Clone(s)
// sort s2 as needed, s won't be affected

This always works but requires a clone of the slice. If the slice elements are large and the slice is long it can require allocating (at least temporarily) large amounts of memory. In this case you could allocate a slice of indexes, and sort that instead.

si := make([]int, len(s))
for i := range si {
  si[i] = i
}
sort.Slice(si, func(i, j) int {
  ei, ej := s[si[i]], s[si[j]]
  return ... // compare ei and ej
})
// to access the i-th sorted element, use s[si[i]]
// the order of s is unaffected

Upvotes: 1

leaf bebop
leaf bebop

Reputation: 8232

You need to make a copy of the original slice.

Use:

newArray := make([]int, len(originalArray))
copy(newArray, originalArray)

or:

newArray := append([]int{}, originalArray...)

Upvotes: 11

Related Questions