Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go按自定义函数排序实例
Go按自定义函数排序实例
作者:--    发布时间:2019-11-20

有时候,我们希望通过除了自然顺序以外的其他方式对集合进行排序。例如,假设我们想按字符串的长度而不是字母顺序对字符串进行排序。下面是go语言中自定义排序的示例。

为了使用go语言中的自定义函数进行排序,我们需要一个相应的类型。这里创建了一个bylength类型,它只是内置 []string类型的别名。

需要实现sort.interface - lenlessswap - 在这个类型上,所以可以使用 sort 包中的一般sort函数。lenswap通常在类型之间是相似的,less保存实际的自定义排序逻辑。在这个例子中,要按照字符串长度的增加顺序排序,因此在这里使用len(s [i])len(s [j])

所有这些都到位后,现在可以通过将原始 fruits 切片转换为bylength来实现自定义排序,然后对该类型切片使用sort.sort()方法。

运行程序根据需要显示按字符串长度排序的列表。

通过遵循创建自定义类型的模式,在该类型上实现三个interface方法,然后在自定义类型的集合上调用sort.sort,可以通过任意函数对go切片进行排序。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

sorting-by-functions.go的完整代码如下所示 -

package main

import "sort"
import "fmt"

// in order to sort by a custom function in go, we need a
// corresponding type. here we've created a `bylength`
// type that is just an alias for the builtin `[]string`
// type.
type bylength []string

// we implement `sort.interface` - `len`, `less`, and
// `swap` - on our type so we can use the `sort` package's
// generic `sort` function. `len` and `swap`
// will usually be similar across types and `less` will
// hold the actual custom sorting logic. in our case we
// want to sort in order of increasing string length, so
// we use `len(s[i])` and `len(s[j])` here.
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])
}

// with all of this in place, we can now implement our
// custom sort by casting the original `fruits` slice to
// `bylength`, and then use `sort.sort` on that typed
// slice.
func main() {
    fruits := []string{"peach", "banana", "kiwi"}
    sort.sort(bylength(fruits))
    fmt.println(fruits)
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run sorting-by-functions.go
[kiwi peach banana]

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册