golang key map 所有_golang 按key字母顺序遍历map

package main

import (

"fmt"

"crypto/md5"

"math/rand"

"sort"

"time"

)

type MapEntryHandler func (string, string)

// func printKeyValue(key string, value string) {

// fmt.Printf("key=%s, value=%s\n", key, value)

// }

// 按字母顺序遍历map

func traverseMapInStringOrder(params map[string]string, handler MapEntryHandler) {

keys := make([]string, 0)

for k, _ := range(params) {

keys = append(keys, k)

}

sort.Strings(keys)

for _, k := range keys {

handler(k, params[k])

}

}

func main() {

params := map[string]string{}

params["captchaId"] = "d094d0ba1af"

params["validate"] = "17faa76f4a"

params["user"] = "mingzhanghui"

params["version"] = "1.0"

params["timestamp"] = "1553435624624"

rand.Seed(time.Now().UnixNano())

params["nounce"] = fmt.Sprintf("%d", rand.Int())

buff := []byte("gmy12345")

params["signature"] = fmt.Sprintf("%x", md5.Sum(buff))

// traverseMapInStringOrder(params, printKeyValue)

traverseMapInStringOrder(params, func (key string, value string) {

fmt.Printf("keys=%s, value=%s\n", key, value)

})

}

运行结果

keys=captchaId, value=d094d0ba1af

keys=nounce, value=5479916053492602771

keys=signature, value=be1776a32cea72e361e72d082252de93

keys=timestamp, value=1553435624624

keys=user, value=mingzhanghui

keys=validate, value=17faa76f4a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值