背景:
产品经理:动态配置的字段,要有有序输出,不要一直变化顺序
我们后端是用Go开发:小猿
Go之母设计的时候就是故意设置随机值,要无序的输出 :小猿
产品经理:我管你那个,你就说能不能干吧
产品经理:别跟我谈条件,10点要演示,距离现在还有15分钟。。。
---------- :小猿
宗旨:满足产品经理的一切不切实际的幻想
例子:
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
// 动态字段
fields := map[string]string{
"username": "张三",
"email": "admin@qq.com",
"age": "18",
"workplace": "科技大厦",
}
// 输出
var result []*response
for k, v := range fields {
result = append(result, &response{
Key: k,
Value: v,
})
}
// json
s, _ := json.Marshal(result)
fmt.Printf(string(s))
}
执行结果:
以上证明了,乱中有序,每次都有小惊喜,人生充满了乐趣,且行且珍惜。(服了,彻底服了,世上还有这种厚颜无耻之人)
解决:
方案一:map无序,slice有序。借slice东风,成就map有序之壮举。
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
// 动态字段
fields := map[string]string{
"username": "张三",
"email": "admin@qq.com",
"age": "18",
"workplace": "科技大厦",
}
// 输出
var result []*response
// 借借slice东风
fieldsSort := []string{"username", "email", "age", "workplace"}
for _, v := range fieldsSort {
if value, ok := fields[v]; ok {
result = append(result, &response{
Key: v,
Value: value,
})
}
}
// json
s, _ := json.Marshal(result)
fmt.Printf(string(s))
}
执行结果:
好吧!到此为止吧 !就这样吧!不要那么多骚操作啦!
还是多思考思考,为什么map一定要无序呢?有序他不香吗?产品经理为啥今天又换了一身衣服?这衣服让我👀无处安放啊?(年轻人,耗子尾汁。。。)
【end】
我为人人,人人为我,美美与共,天下大同。