• Go Map有序输出


    背景:

            产品经理:动态配置的字段,要有有序输出,不要一直变化顺序

                                                                                                                我们后端是用Go开发:小猿

                                                          Go之母设计的时候就是故意设置随机值,要无序的输出 :小猿

          产品经理:我管你那个,你就说能不能干吧

                                                                         这话说的,干肯定能干。  只不过需要耗费时间:小猿

         产品经理:别跟我谈条件,10点要演示,距离现在还有15分钟。。。

                                                                                                                                      ---------- :小猿

                                                                                                             


                                          宗旨:满足产品经理的一切不切实际的幻想 


    例子:

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. )
    6. type response struct {
    7. Key string `json:"key"`
    8. Value string `json:"value"`
    9. }
    10. func main() {
    11. // 动态字段
    12. fields := map[string]string{
    13. "username": "张三",
    14. "email": "admin@qq.com",
    15. "age": "18",
    16. "workplace": "科技大厦",
    17. }
    18. // 输出
    19. var result []*response
    20. for k, v := range fields {
    21. result = append(result, &response{
    22. Key: k,
    23. Value: v,
    24. })
    25. }
    26. // json
    27. s, _ := json.Marshal(result)
    28. fmt.Printf(string(s))
    29. }

    执行结果:

      

     

    以上证明了,乱中有序,每次都有小惊喜,人生充满了乐趣,且行且珍惜。(服了,彻底服了,世上还有这种厚颜无耻之人)

    解决: 

            方案一:map无序,slice有序。借slice东风,成就map有序之壮举。

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. )
    6. type response struct {
    7. Key string `json:"key"`
    8. Value string `json:"value"`
    9. }
    10. func main() {
    11. // 动态字段
    12. fields := map[string]string{
    13. "username": "张三",
    14. "email": "admin@qq.com",
    15. "age": "18",
    16. "workplace": "科技大厦",
    17. }
    18. // 输出
    19. var result []*response
    20. // 借借slice东风
    21. fieldsSort := []string{"username", "email", "age", "workplace"}
    22. for _, v := range fieldsSort {
    23. if value, ok := fields[v]; ok {
    24. result = append(result, &response{
    25. Key: v,
    26. Value: value,
    27. })
    28. }
    29. }
    30. // json
    31. s, _ := json.Marshal(result)
    32. fmt.Printf(string(s))
    33. }

    执行结果:

     

    好吧!到此为止吧 !就这样吧!不要那么多骚操作啦!

    还是多思考思考,为什么map一定要无序呢?有序他不香吗?产品经理为啥今天又换了一身衣服?这衣服让我👀无处安放啊?(年轻人,耗子尾汁。。。)

                                                                      【end】


    我为人人,人人为我,美美与共,天下大同。

  • 相关阅读:
    gRPC之拦截器与元数据
    智能驾驶功能软件平台设计规范第三部分:预测功能服务接口
    @Validated与@Valid
    nodejs+vue 大学生就业管理系统
    136.如何进行离线计算-2
    Spring IOC 容器官方文档翻译笔记
    C#:实现点是否在多边形内算法​(附完整源码)
    3A通过PMP考试有多大比例?
    操作系统学习笔记3 | 操作系统简史
    618京东到家APP-门详页反爬实战 | 京东云技术团队
  • 原文地址:https://blog.csdn.net/qq_37837134/article/details/127759090