Error in sorting structs

Hello, I have the following code:

https://play.golang.org/p/VTkYtxJfimq

But i cannot sort it like that:
colorado578
YMCA1
YMCA2

(sort first by filename and then by index)

Any idea?

regards

There are some considerations:

  1. You should transform it or to upper case or to lower case for correct comparison.
  2. You should compare by index only if strings are equal.

I fixed it:
https://play.golang.org/p/kL5lQVpfBjQ

If you convert the index to a string and concatenate it to the uppercase of the filename, you can compare those simply and arrive at the desired order:
https://play.golang.org/p/ckO3bH-ilfY

I have no idea about the difference between this and just taking the sort in two separate passes though:
https://play.golang.org/p/grnQ199W6-0

I suspect it would depend on the length of your slice as the second version passes through the slice twice as many times I would think.

No, that won’t work, e.g. “YMCA12” will come before “YMCA2” if you simply concatenate, while if you check for filename first and then for index the order will be correct.

You’re right, I was using your example and not thinking it through, sorry beginner here. Lesson learned :frowning: . However, the second example, passing it through twice, should still work.

https://play.golang.org/p/7VW6N18OHb6

Thanks!

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