分享
  1. 首页
  2. 文章

通过sort包的使用,理解golang接口的应用

Cedrus · · 1199 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

在go语言的应用中,涉及到排序,通常使用sort包来实现,sort包中实现了3种基本的排序算法:插入排序,快排和堆排序,这里不打算探讨排序算法,而会通过使用sort包,来理解interface的应用。

sort.go

type Interface interface {
 // Len is the number of elements in the collection.
 Len() int
 // Less reports whether the element with
 // index i should sort before the element with index j.
 Less(i, j int) bool
 // Swap swaps the elements with indexes i and j.
 Swap(i, j int)
}

Interface接口中这三种方法是排序这个需求抽象出来的,任何实现了这三个方法的类型,都实现了这个接口,可以使用这里面的排序方法,避免了重新定义各种不同参数的Sort函数。其中Len是要排序集合的个数,作为选择合适排序方法的条件,Less用于判断index为i和j的两元素的大小,Swap用于交换两个元素。
sort包里面已经实现了[]int,[]float64,[]string的排序。

// StringSlice attaches the methods of Interface to []string, sorting in increasing order.
type StringSlice []string
func (p StringSlice) Len() int { return len(p) }
func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

都是升序。应用如下:

package main
import "fmt"
import "sort"
func main() {
 a := sort.IntSlice{2, 4, 1, 3}
 a.Sort()
 b := []int{6, 5, 8, 4}
 sort.Ints(b)
 fmt.Println(a)
 fmt.Println(b)
}

如果是具体的某个结构体的排序,就需要自己实现Interface了。以Amount降序排序道具列表的例子如下:

package main
import "fmt"
import . "sort"
type Item struct {
 Id int32
 Name string
 Amount int32
}
type Items []Item
func (items Items) Len() int {
 return len(items)
}
func (items Items) Less(i, j int) bool {
 if items[i].Amount < items[j].Amount {
 return false
 }
 return true
}
func (items Items) Swap(i, j int) {
 items[i], items[j] = items[j], items[i]
}
func main() {
 items := Items{{1, "item_0", 3}, {2, "Item_1", 1}, {3, "item_2", 2}}
 Sort(items)
 fmt.Println(items)
}

运行结果:
[{1 item_0 3} {3 item_2 2} {2 Item_1 1}]
总结,golang用interface来实现类、抽象、多态的编程思想,平时开发中,多用interface的特性来设计功能能让代码更简洁,更合理。


有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:Cedrus

查看原文:通过sort包的使用,理解golang接口的应用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1199 次点击
上一篇:go语言
下一篇:Go 内存管理
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏