[Go] mapのソート
配列のソートは強力だけど、
mapのソートは、JavaのTreeSetみたいには行かないようだね。
mapのソートは、JavaのTreeSetみたいには行かないようだね。
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 Shop struct { | |
Code string | |
} | |
type Shops []*Shop | |
func (d Shops) Len() int { | |
return len(d) | |
} | |
func (d Shops) Swap(i, j int) { | |
d[i], d[j] = d[j], d[i] | |
} | |
func (d Shops) Less(i, j int) bool { | |
return d[i].Code < d[j].Code | |
} | |
func main() { | |
shopMap := make(map[string]*Shop) | |
shopMap["xx"] = &Shop{Code: "xx"} | |
shopMap["hoge"] = &Shop{Code: "hoge"} | |
shopMap["fuga"] = &Shop{Code: "fuga"} | |
var keys Shops | |
for _, s := range shopMap { | |
keys = append(keys, s) | |
} | |
sort.Sort(keys) | |
fmt.Printf("%t", keys) | |
} |
コメント
コメントを投稿