Advertisement
cwchen

[Go] Sorting demo.

Nov 21st, 2017
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.39 KB | None | 0 0
  1. package main
  2.  
  3. import "sort"
  4. import "fmt"
  5.  
  6. type ByLength []string
  7.  
  8. func (s ByLength) Len() int {
  9.     return len(s)
  10. }
  11. func (s ByLength) Swap(i, j int) {
  12.     s[i], s[j] = s[j], s[i]
  13. }
  14. func (s ByLength) Less(i, j int) bool {
  15.     return len(s[i]) < len(s[j])
  16. }
  17.  
  18. func main() {
  19.     fruits := []string{"peach", "banana", "kiwi"}
  20.     sort.Sort(ByLength(fruits))
  21.     fmt.Println(fruits)
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement