Skip to content

Instantly share code, notes, and snippets.

@dnutiu
Last active September 3, 2023 02:10
Show Gist options
  • Save dnutiu/a899e48c95ff80fe98bada566e03251e to your computer and use it in GitHub Desktop.
Save dnutiu/a899e48c95ff80fe98bada566e03251e to your computer and use it in GitHub Desktop.
How to sort custom structs in golang.
package main
import (
"fmt"
"sort"
)
type Student struct {
Name string
Grade int
}
type Students []Student
func (s Students) Len() int {
return len(s)
}
func (s Students) Less(i, j int) bool {
return s[i].Grade < s[j].Grade
}
func (s Students) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
fmt.Println("Sorting Demo in Go")
var students Students = Students{
{"Denis", 12},
{"Ascolin", 50},
{"IIsus", 99},
{"Mario", 2},
{"Gogaie", 37},
{"Dentistul", 76},
}
fmt.Println(students)
fmt.Println(sort.IsSorted(students))
sort.Sort(students)
fmt.Println(students)
fmt.Println(sort.IsSorted(students))
sort.Sort(sort.Reverse(students))
fmt.Println(students)
}
@MrDjeb
Copy link

MrDjeb commented Oct 19, 2022

@yasarboutiqaat I love you too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment