I'm just getting to grips with Go (started two days ago and wrote less than 1000 lines), and I'm still wondering about some idioms.
I needed to sort a slice of strings by descending length. I did like so :
func ... {
... do business ...
sort.Sort(stringsLongestFirst(severalThousandStrings))
... carry on and be happy, because it works ...
}
type stringsLongestFirst []string
func (b stringsLongestFirst) Len() int { return len(b) }
func (b stringsLongestFirst) Less(i, j int) bool { return len(b[i]) > len(b[j]) }
func (b stringsLongestFirst) Swap(i, j int) { b[j], b[i] = b[i], b[j] }
First of all I wonder if this is the most idiomatic way to do it.
And then, most of all, I wonder about what happens under the hood when I write stringsLongestFirst(severalThousandStrings)
. Does the string slice somehow get smartly reinterpreted as a stringsLongestFirst
type, or do I have to count with some copying overhead ?
(edited : removed the excerpt from the specification, that was ill-suited to the case at hand)