Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Last active July 27, 2022 18:30
Show Gist options
  • Save hassaku63/27400eba684613878738c680178bc8ed to your computer and use it in GitHub Desktop.
Save hassaku63/27400eba684613878738c680178bc8ed to your computer and use it in GitHub Desktop.
[Golang] map, struct を要素に持つリストをソートする例
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())
}
}
@hassaku63
Copy link
Author

$ go run main.go
2022/07/28 xx:xx:xx --- sort maps ---
2022/07/28 xx:xx:xx b 10
2022/07/28 xx:xx:xx x s
2022/07/28 xx:xx:xx c 1
2022/07/28 xx:xx:xx -- by key
2022/07/28 xx:xx:xx b 10
2022/07/28 xx:xx:xx c 1
2022/07/28 xx:xx:xx x s
2022/07/28 xx:xx:xx --- sort structs ---
2022/07/28 xx:xx:xx -- by Id
2022/07/28 xx:xx:xx {"Id":1,"Firstname":"bbb","Lastname":"yyy"}
2022/07/28 xx:xx:xx {"Id":2,"Firstname":"aaa","Lastname":"zzz"}
2022/07/28 xx:xx:xx {"Id":3,"Firstname":"ccc","Lastname":"xxx"}
2022/07/28 xx:xx:xx -- by Firstname
2022/07/28 xx:xx:xx {"Id":2,"Firstname":"aaa","Lastname":"zzz"}
2022/07/28 xx:xx:xx {"Id":1,"Firstname":"bbb","Lastname":"yyy"}
2022/07/28 xx:xx:xx {"Id":3,"Firstname":"ccc","Lastname":"xxx"}
2022/07/28 xx:xx:xx -- by Lastname
2022/07/28 xx:xx:xx {"Id":3,"Firstname":"ccc","Lastname":"xxx"}
2022/07/28 xx:xx:xx {"Id":1,"Firstname":"bbb","Lastname":"yyy"}
2022/07/28 xx:xx:xx {"Id":2,"Firstname":"aaa","Lastname":"zzz"}

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