Last active
September 3, 2023 02:10
-
-
Save dnutiu/a899e48c95ff80fe98bada566e03251e to your computer and use it in GitHub Desktop.
How to sort custom structs in golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
you can use sort.Slice() which can sort custom types...
I love you
you can use sort.Slice() which can sort custom types...
@yasarboutiqaat I love you +1.
@yasarboutiqaat I love you too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can use sort.Slice() which can sort custom types...