go 101
1. golang unmarshal 的坑
func TestJSON(t *testing.T) {
m := map[string]string{}
//解析正则表达式,如果成功返回解释器
s1 := `{"f1": "111", "f2": "222", "f1": "333"}`
err := json.Unmarshal([]byte(s1), &m)
if err != nil {
fmt.Println("---unmarshal fialed--")
}
bytes, _ := json.Marshal(m)
fmt.Println("---unmarshal success--", string(bytes))
}
---unmarshal success-- {"f1":"333","f2":"222"}
结论,duplicate field 的字符串,unmarshal 不会报错,如果要使用 json 结构,需要使用 unmarshal 后结构
2. golang fmt.Printf []byte 和 string
go fmt.Printf("%s", message) 其中message 是[]byte ,输出一堆乱码
当使用 fmt.Printf("%s", message) 输出乱码时,通常是因为 message 中包含了非 ASCII 字符或者不可打印字符,导致它们在终端中无法正确显示。
在 Go 中,fmt.Printf("%s", ...) 用于格式化输出字符串,但是在处理 []byte 时,它假定 []byte 中的内容是以 ASCII 字符编码的。如果 []byte 中包含了非 ASCII 字符,fmt.Printf 可能会出现乱码。
解决方式是 先转换为string, 然后输出