B
B
Ben L2021-08-01 18:48:05
go
Ben L, 2021-08-01 18:48:05

How to sort in Go?

Suppose I have a slice of bytes. How to sort it in Go?

arr := []byte{4, 3, 2, 1, 6, 3, 77, 8,3}
sort.Slice(arr, func(i, j int) bool {
  return arr[i] < arr[j]
})
fmt.Println(arr)

Is this the only way?
Is it possible to declare the comparison function 1 time and reuse it if we have to compare several slices?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2021-08-01
@linesb

If you need a function, you can do it like this

func SortBytes(arr []byte) {
    sort.Slice(arr, func(i, j int) bool {
        return arr[i] < arr[j]
    })
}
// потом использовать вот так
arr := []byte{4, 3, 2, 1, 6, 3, 77, 8,3}
sortBytes(arr)
fmt.Println(arr)

But I would use the one you have
sort.Slice(arr, func(i, j int) bool {
  return arr[i] < arr[j]
})
fmt.Println(arr)

R
Roman Mirilaczvili, 2021-08-01
@2ord

sorter := func(i, j int) bool {
    return arr[i] < arr[j]
  }
  sort.Slice(arr, sorter)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question