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

在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的特性来设计功能能让代码更简洁,更合理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值