Created
May 5, 2019 09:52
-
-
Save koyo-miyamura/f49d7b8f1758c8ce51ea344bf6342046 to your computer and use it in GitHub Desktop.
Goでカスタムsort
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 User struct { | |
Name string | |
Age int | |
} | |
type Users []User | |
func (u Users) Len() int { | |
return len(u) | |
} | |
func (u Users) Less(i, j int) bool { | |
return u[i].Age > u[j].Age | |
} | |
func (u Users) Swap(i, j int) { | |
u[i], u[j] = u[j], u[i] | |
} | |
func main() { | |
var users Users | |
users = []User{ | |
{ | |
Name: "Ando", | |
Age: 20, | |
}, | |
{ | |
Name: "Bob", | |
Age: 24, | |
}, | |
} | |
fmt.Println(users) | |
sort.Sort(users) | |
fmt.Println(users) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment