Skip to content

Instantly share code, notes, and snippets.

@AnirudhaS
Created October 7, 2017 23:49
Show Gist options
  • Select an option

  • Save AnirudhaS/25f5ce317c970d44a3198b6e2b9b8be6 to your computer and use it in GitHub Desktop.

Select an option

Save AnirudhaS/25f5ce317c970d44a3198b6e2b9b8be6 to your computer and use it in GitHub Desktop.
Basic example to demonstrate implementation of Generics in Go using interfaces.
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type PersonList []Person
func (s PersonList) Len() int {
return len(s)
}
func (s PersonList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s PersonList) Less(i, j int) bool {
if s[i].Age == s[j].Age {
// Default string comparison returns result by alphabetical order.
return s[i].Name < s[j].Name
}
return s[i].Age < s[j].Age
}
func main() {
persons := PersonList{
Person{Name: "James", Age: 23},
Person{Name: "Anthony", Age: 23},
Person{Name: "Bob", Age: 24},
Person{Name: "Charles", Age: 24},
Person{Name: "Chris", Age: 32},
Person{Name: "David", Age: 39},
}
fmt.Println("Before sort: ", persons)
sort.Sort(persons)
fmt.Println("After Sort: ", persons)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment