Reorder a slice by a target slice of indexes without looping

Considering the following two slices

x := []int{10, 20, 30}
idx := []int{0, 2, 1}

can I reorder the slice x using the idx as the desired order (i.e. [10, 30, 20]), without using a loop?
Currently I am doing

x := []int{10, 20, 30}
idx := []int{0, 2, 1}

var result []int
for _, s := range idx {
	result = append(result, x[s])

In other languages (e.g. R, Julia,…) you would just do x[idx]

Hi @Pisistrato,

Other languages have lots and lots of convenience functions and magic commands and shortcuts built in to make writing code comfortable, at the expense of making reading more cryptic.

Go does not work the way. But you can take your loop and put it into a function, and then you have slice reordering without a loop, just like in R or Julia. :slight_smile:

(To explain what I mean with making reading more cryptic: To me, x[idx] looks exactly like a simple index operation looks like in Go. If this syntax represents a complete restructuring of x based on an idx whose contents are expected to be a set of unique integers, then this is quite a lot of context information that is crammed into the expression x[idx]. I’d rather read this operation with a proper name, e.g. x.ReorderBy(idx).)

1 Like

Except that, until generics, you have to rewrite that code for every slice type.

Counting the days…


counting with you… lol

Thanks for the explanation.
Indeed, as @mje pointed out, for someone like me, who does not code in Go 24/7, it is a bit annoying to rewrite code :stuck_out_tongue:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.