× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
Martin Czygan
May 05, 2015
<p>You could implement <code>Len</code>, <code>Swap</code> and <code>Less</code> for a custom type. An example is given here: <a href="https://gobyexample.com/sorting-by-functions" rel="nofollow">https://gobyexample.com/sorting-by-functions</a></p> <p>Here's how you could sort by key for your example: <a href="http://play.golang.org/p/i6-e4I7vih" rel="nofollow">http://play.golang.org/p/i6-e4I7vih</a></p> <pre><code>import ( "fmt" "sort" ) type Pair struct { Key string Value int } type ByKey []Pair func (s ByKey) Len() int { return len(s) } func (s ByKey) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByKey) Less(i, j int) bool { return s[i].Key &lt; s[j].Key } func main() { pairs := []Pair{{"a", 1}, {"b", 0}, {"c", 2}} // Sort by Key sort.Sort(ByKey(pairs)) fmt.Println(pairs) // [{a 1} {b 0} {c 2}] } </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29693708/Sort%20pair%20in%20GoLang/29693787">Stack Overflow</a>.</p>
comments powered by Disqus