0116-Go-自定义排序

环境

  • Time 2022-08-25
  • Go 1.19

前言

说明

参考:https://gobyexample.com/sorting-by-functions

目标

使用 Go 语言的自定义排序。

示例

package main

import (
    "fmt"
    "sort"
)

type byLength []string

func (s byLength) Len() int {
    return len(s)
}
func (s byLength) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
    return len(s[i]) < len(s[j])
}

func main() {
    fruits := []string{"peach", "banana", "kiwi"}
    sort.Sort(byLength(fruits))
    fmt.Println(fruits)
}

总结

使用 Go 语言的自定义排序。

附录

posted @ 2022-11-27 19:31  jiangbo4444  阅读(16)  评论(0)    收藏  举报