Loading... ## golang结构体omitempty和-的作用和区别 ### omitempty的作用 ```go type Demo struct { Code int `json:"code,omitempty"` Msg string `json:"msg"` } ``` 当Code为默认值的时候他就会在序列化的时候被忽略掉 > 序列化 ```go if marshal, err := json.Marshal(&Demo{}); err != nil { fmt.Println(err) } else { fmt.Println(string(marshal)) } ``` > 返回值`{"msg":""}` 可见,code被忽略掉了,而msg加上omitempty不赋值也是会被忽略掉 ### `json:"-"`的作用 ```go type Demo struct { Code int `json:"code,omitempty"` Msg string `json:"-"` } ``` ```go if marshal, err := json.Marshal(&Demo{ Code: 666, Msg: "茶白", }); err != nil { fmt.Println(err) } else { fmt.Println(string(marshal)) } ``` > 返回值 `{"code":666}` 可见这个msg 赋值不赋值都会被忽略掉 ```go type Demo struct { Code int `db:"code"` Msg string `db:"-"` } ``` 此时msg在mysql中就不会参与 ### omitempty和 - 的区别 显而易见,一个是序列化时,字段是默认值的会被忽略,另外一个是不参与序列化 最后修改:2022 年 07 月 24 日 © 允许规范转载 打赏 赞赏作者 微信 赞 0 如果觉得我的文章对你有用,请随意赞赏