package main
import (
"fmt"
"sort"
)
func MapKeySort[T int8 | int16 | int32 | int64 | int | float32 | float64 | string | bool | interface{}](m map[string]T, options ...string) string {
// 将map中全部的key到切片中
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
// 对切片进行排序
sort.Strings(keys)
// 循环拼接返回
result := ""
for _, item := range keys {
if len(options) > 0 {
if result != "" {
result += fmt.Sprintf("%s%v", options[0], fmt.Sprintf("%s=%v", item, m[item]))
} else {
result += fmt.Sprintf("%s=%v", item, m[item])
}
} else {
if result != "" {
result += fmt.Sprintf("&%v", fmt.Sprintf("%s=%v", item, m[item]))
} else {
result += fmt.Sprintf("%s=%v", item, m[item])
}
}
}
return result
}
func main() {
map1 := map[string]string{
"a": "1",
"b": "2",
"ab": "3",
"abcd": "4",
}
fmt.Println(MapKeySort(map1))
}
05-20
1883
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-07
292
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)