-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
54 lines (47 loc) · 1.16 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Books sorts and prints a collection of books.
// For more see
// - https://pkg.go.dev/sort#pkg-examples
// - https://github.com/adonovan/gopl.io/blob/master/ch7/sorting
package main
import (
"fmt"
"os"
"sort"
"strings"
"text/tabwriter"
"time"
)
type Book struct {
Title string
Authors
Age int
}
type Authors []string
func (as Authors) String() string {
return strings.Join(as, ", ")
}
func age(yearBorn int) (yearsOld int) {
yearNow := time.Now().Year()
return yearNow - yearBorn
}
func printBooks(books []Book) {
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
format := "%v\t%v\t%v\n"
fmt.Fprintf(tw, format, "Age", "Title", "Authors")
fmt.Fprintf(tw, format, "---", "-----", "-------")
for _, book := range books {
fmt.Fprintf(tw, format, book.Age, book.Title, book.Authors)
}
tw.Flush()
}
func main() {
books := []Book{
{"The Lord of The Rings", Authors{"Tolkien"}, age(1954)},
{"The Go Programming Language", Authors{"Kernighan", "Donovan"}, age(2015)},
{"The Phoenix Project", Authors{"Kim", "Behr", "Spafford"}, age(2013)},
}
sort.Slice(books, func(i, j int) bool {
return books[i].Age < books[j].Age
})
printBooks(books)
}