Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(79)

Unified Diff: 2014/go4gophers/organs3.go

Issue 97780044: code review 97780044: go.talks: add "Go for Gophers" slides (Closed)
Patch Set: diff -r 2b96b82cd80d https://code.google.com/p/go.talks Created 9 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « 2014/go4gophers/organs2.go ('k') | 2014/go4gophers/reader.go » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: 2014/go4gophers/organs3.go
===================================================================
new file mode 100644
--- /dev/null
+++ b/2014/go4gophers/organs3.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "fmt"
+ "sort"
+)
+
+type Organ struct {
+ Name string
+ Weight Grams
+}
+
+func (o *Organ) String() string { return fmt.Sprintf("%v (%v)", o.Name, o.Weight) }
+
+type Grams int
+
+func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
+
+type Organs []*Organ
+
+func (s Organs) Len() int { return len(s) }
+func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+type ByName struct{ Organs }
+
+func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
+
+type ByWeight struct{ Organs }
+
+func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
+
+func main() {
+ s := []*Organ{
+ {"brain", 1340},
+ {"heart", 290},
+ {"liver", 1494},
+ {"pancreas", 131},
+ {"spleen", 162},
+ }
+
+ // START OMIT
+ sort.Sort(Reverse(ByWeight{s})) // HL
+ printOrgans("Organs by weight (descending)", s)
+
+ sort.Sort(Reverse(ByName{s})) // HL
+ printOrgans("Organs by name (descending)", s)
+ // STOP OMIT
+}
+
+func printOrgans(t string, s []*Organ) {
+ fmt.Printf("%s:\n", t)
+ for _, o := range s {
+ fmt.Printf(" %v\n", o)
+ }
+}
+
+func Reverse(data sort.Interface) sort.Interface {
+ return &reverse{data}
+}
+
+type reverse struct{ sort.Interface }
+
+func (r reverse) Less(i, j int) bool {
+ return r.Interface.Less(j, i) // HL
+}
« no previous file with comments | « 2014/go4gophers/organs2.go ('k') | 2014/go4gophers/reader.go » ('j') | no next file with comments »

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b