Go的sort接口实现
package main
import (
"fmt"
"sort"
"time"
)
type Track struct {
Title string
Artist string
Album string
Year int
Length time.Duration
}
type Tracks []Track
func ParseDurationTime(s string) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
return ParseDurationTime("0s")
} else {
return d
}
}
// {{{ implementation of Sort interface
// Len is the number of elements in the collection.
func (x Tracks) Len() int {
return len(x)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (x Tracks) Less(i, j int) bool {
return x[i].Year < x[j].Year
}
// Swap swaps the elements with indexes i and j.
func (x Tracks) Swap(i, j int) {
x[i], x[j] = x[j], x[i]
}
// end implementation of Sort interface }}}
var tracks = Tracks{
{Title: "C#", Artist: "Delu", Album: "Reading", Year: 2017, Length: ParseDurationTime("3m38s")},
{Title: "Go", Artist: "Anderson", Album: "Reading", Year: 2018, Length: ParseDurationTime("3m38s")},
{Title: "Java Bible", Artist: "Js", Album: "Reading", Year: 2016, Length: ParseDurationTime("3m38s")}}
//main function
func main() {
sort.Sort(tracks)
for key, value := range tracks {
fmt.Printf("%v:%v \n", key, value)
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
计算机程序设计艺术・卷3
[美] 高德纳(Donald E. Knuth) / 贾洪峰 / 人民邮电出版社 / 2017-2 / 198.00元
《计算机程序设计艺术》系列被公认为计算机科学领域的权威之作,深入阐述了程序设计理论,对计算机领域的发展有着极为深远的影响。本书为该系列的第3卷,全面讲述了排序和查找算法。书中扩展了卷1中数据结构的处理方法,并对各种算法的效率进行了大量的分析。一起来看看 《计算机程序设计艺术・卷3》 这本书的介绍吧!