《The Go Programming Language》 笔记
package sorting
import (
"fmt"
"os"
"sort"
"text/tabwriter"
"time"
)
type Track struct {
Title string
Artist string
Album string
Year int
Length time.Duration
}
type customSort struct {
t []*Track
less func(x,y *Track) bool
}
func (cs *customSort) Len() int { return len(cs.t) }
func (cs *customSort) Less(i,j int) bool { return cs.less(cs.t[i],cs.t[j]) }
func (cs *customSort) Swap(i,j int) { cs.t[i],cs.t[j] = cs.t[j],cs.t[i] }
func SortTrack(tracks []*Track) {
sort.Sort(&customSort{tracks,func(x,y *Track) bool {
if x.Title != y.Title {
return x.Title < y.Title
}
if x.Year != y.Year {
return x.Year < y.Year
}
if x.Length != y.Length {
return x.Length < y.Length
}
return false
}})
printTracks(tracks)
}
type byArtist []*Track
func (x byArtist) Len() int { return len(x) }
func (x byArtist) Less(i,j int) bool { return x[i].Artist < x[j].Artist }
func (x byArtist) Swap(i,j int) { x[i],x[j] = x[j],x[i] }
func SortTracksByArtist(tracks []*Track) {
sort.Sort(byArtist(tracks))
printTracks(tracks)
}
func printTracks(tracks []*Track) {
const format = "%v\t%v\t%v\t%v\t%v\t\n"
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2,' ', 0)
fmt.Fprintf(tw,format,"Title","Artist","Album","Year","Length")
fmt.Fprintf(tw,"-----","-----")
for _,t := range tracks {
fmt.Fprintf(tw,t.Title,t.Artist,t.Album,t.Year,t.Length)
}
tw.Flush()
}
var tracks = []*sorting.Track{
{"Go","Deliah","From the Roots Up", 2012,length("3m38s")},{"Go","Moby", 1992,length("3m37s")},{"Go Ahead","Alicia Keys","As I Am", 2007,length("4m36s")},{"Ready 2 Go","Martin Soleving","Smash", 2011,length("4m24s")},}
func length(ts string) time.Duration {
d,err := time.ParseDuration(ts)
if err != nil {
panic(ts)
}
return d
}
func main() {
sorting.SortTrack(tracks)
}