Re:Go by Example
by colin_mccabe on Friday January 17, 2014 @07:03PM
(#7079348)
Can any "idiomatic" Go programmers here give a better example of how you would do this?
Sure.
sort.Sort(sort.Reverse(sort.StringSlice(vs)));
Re:Go by Example
by colin_mccabe on Saturday January 18, 2014 @03:53AM
(#7080562)
Oops, 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))You 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.
Re:Go by Example
by jamesaguilar on Friday January 17, 2014 @01:45PM
(#7077611)
This is the idiomatic way. It's actually the only way.
Can any "idiomatic" Go programmers here give a better example of how you would do this?