O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter11/recipe07.
  2. Navigate to the directory.
  3. Create the file sort.go with the following content:
        package main        import (          "fmt"          "sort"        )        type Gopher struct {          Name string          Age int        }        var data = []Gopher{          {"Daniel", 25},          {"Tom", 19},          {"Murthy", 33},        }        type Gophers []Gopher        func (g Gophers) Len() int {          return len(g)        }        func (g Gophers) Less(i, j int) bool {          return g[i].Age > g[j].Age        }        func (g Gophers) Swap(i, j int) {          tmp := g[j]          g[j] = g[i]          g[i] = tmp        }        func main() {          sort.Slice(data, func(i, j int) bool {            return sort.StringsAreSorted([]string{data[i].Name,                                       data[j].Name})          })          fmt.Printf("Sorted by name: %v\n", data)          gophers := Gophers(data)          sort.Sort(gophers) fmt.Printf("Sorted by age: %v\n", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required