Last active
July 27, 2022 18:30
-
-
Save hassaku63/27400eba684613878738c680178bc8ed to your computer and use it in GitHub Desktop.
[Golang] map, struct を要素に持つリストをソートする例
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 ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"sort" | |
) | |
type Person struct { | |
Id int | |
Firstname string | |
Lastname string | |
} | |
func (p *Person) String() string { | |
// ナイーブな実装 | |
// return fmt.Sprintf("{Id: %d, Firstname: \"%s\", Lastname: \"%s\"}", p.Id, p.Firstname, p.Lastname) | |
// Json encode して返す | |
b, err := json.Marshal(p) | |
if err != nil { | |
panic(fmt.Sprintf("marshal error: %s", p.String())) | |
} | |
return string(b) | |
} | |
func main() { | |
log.Println("--- sort maps ---") | |
dict := map[string]any{"c": 1, "b": 10, "x": "s"} | |
for k, v := range dict { | |
log.Println(k, v) | |
} | |
log.Println("-- by key") | |
keys := make([]string, 0, len(dict)) | |
for k := range dict { | |
keys = append(keys, k) | |
} | |
sort.Strings(keys) | |
for _, k := range keys { | |
log.Println(k, dict[k]) | |
} | |
log.Println("--- sort structs ---") | |
persons := []Person{ | |
{Id: 2, Firstname: "aaa", Lastname: "zzz"}, | |
{Id: 1, Firstname: "bbb", Lastname: "yyy"}, | |
{Id: 3, Firstname: "ccc", Lastname: "xxx"}, | |
} | |
log.Println("-- by Id") | |
sort.Slice(persons, func(i, j int) bool { | |
return persons[i].Id < persons[j].Id | |
}) | |
for _, p := range persons { | |
log.Println(p.String()) | |
} | |
log.Println("-- by Firstname") | |
sort.Slice(persons, func(i, j int) bool { | |
return persons[i].Firstname < persons[j].Firstname | |
}) | |
for _, p := range persons { | |
log.Println(p.String()) | |
} | |
log.Println("-- by Lastname") | |
sort.Slice(persons, func(i, j int) bool { | |
return persons[i].Lastname < persons[j].Lastname | |
}) | |
for _, p := range persons { | |
log.Println(p.String()) | |
} | |
} |
Author
hassaku63
commented
Jul 27, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment