4 ms·
Wow, yeah. This is pretty bad. The example doesn't even make logical sense. Why is ByLength a type? Shouldn't you just want to pass in an array? Can any "
by natural219 13y ago
Wow, yeah. This is pretty bad. The example doesn't even make logical sense. Why is ByLength a type? Shouldn't you just want to pass in an array?
Can any "idiomatic" Go programmers here give a better example of how you would do this?
- colin_mccabe 13y agoCan any "idiomatic" Go programmers here give a better example of how you would do this? Sure. sort.Sort(sort.Reverse(sort.StringSlice(vs)));
- colin_mccabe 13y agoOops, I looked at the Python code again, and it seems to be sorting the strings by their length, not reversing the sort order like I did. Sorry, I didn't look at it very carefully earlier. Anyway, the easiest thing to do is probably write a wrapper type around StringSlice using Go's anonymous struct syntax. You only need to implement LessThan, since StringSlice already implements the other two. type StringSliceByLength struct { sort.StringSlice; } func (s StringSliceByLength) LessThan(i, j int) bool { return len(s.StringSlice[i]) < len(s.StringSlice[j]); } Sort.sort(StringSliceByLength(vs))
- frou_dh 13y agoYou can't put methods on a type from a different package (or in this case a builtin type). Instead of methods, you could of course write normal functions taking []string, but only methods can fulfil interfaces.
- jamesaguilar 13y agoThis is the idiomatic way. It's actually the only way.