这么快就第三期了,算下来这期包括前几期我的《Go 语言开发小技巧 &易错点 100 例》已经凑够了 15 个!任务完成率 15%!继续加油!
往期回顾:
本期看点(技巧类用【技】表示,易错点用【易】表示):
(1)Go omitempty 关键字【技】
(2)Go 进行 JSON Marshal 序列化时需要注意的问题【易】
(3)Go iota 关键字【技】
下面是正文:
1 Go omitempty 关键字【技】
大家在将 Go 语言里面的结构体类型转化为 JSON 数据类型时有没有过这样的需求:
当结构体有多个字段时,仅赋值部分字段,让其余字段都为空,并且在 JSON Marshal 时不序列化为空的字段。
代码表示:
type Student struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"`}
func main() { // 只赋值Id、Name,不赋值Age属性 stu := Student{ Id: 1, Name: "zs", } bytes, _ := json.Marshal(stu) fmt.Println(string(bytes))}
复制代码
运行结果:
{"id":1,"name":"zs","age":0}
复制代码
但是我们想要的结果是
这个时候,就使用需要使用到这个关键字:omitempty,该关键字作用:
接下来我们就来实验下:
type Student struct { Id int `json:"id,omitempty"` Name string `json:"name,omitempty"` Age int `json:"age,omitempty"` Address *string `json:"address,omitempty"` Like []string `json:"list,omitempty"` Love [1]string `json:"love,omitempty"`}
func main() { // 只赋值Id、Name,不赋值Age属性 stu := Student{ Id: 1, Name: "zs", } bytes, _ := json.Marshal(stu) fmt.Println(string(bytes))}
复制代码
输出的结果:
{"id":1,"name":"zs","love":[""]}
复制代码
2 Go JSON Marshal 需要注意的问题【易】
Go 语言有一个约定,就是首字母大写的属性或函数才能够外部可见,外部指的是包外部,除此之外在 JSON Marshal 中也需要用到类似的约定:只有结构体的属性属于外部可见时才能够进行 JSON 序列化。
直接上代码:
type Object struct { name string `json:"name"` method string `json:"method"`}
func main() { obj := Object{ name: "zs", method: "play", } bytes, _ := json.Marshal(obj) fmt.Println(string(bytes))}
复制代码
打印结果:
解决方式就是将结构体的属性名改成大写,之后就可以了:
type Object struct { Name string `json:"name"` Method string `json:"method"`}
复制代码
3 Go iota 关键字【技】
概念:iota 是 go 语言的常量计数器,只能在常量的表达式中使用,多用于代替枚举类型。
注意点:
(1)iota 在 const 关键字中定义,默认为 0,并且以同一个 const 中多个 iota 只能默认为 0 一次。
(2)const 中每新增一行常量声明将使 iota 按规则计数一次。
使用方式:
const ( i1 = iota i2 _ //丢弃该值 i4)
const ( n1 = iota * 10 n2 n3)
func main() { fmt.Println(i1) fmt.Println(i2) fmt.Println(i4)
fmt.Println(n1) fmt.Println(n2) fmt.Println(n3)}
复制代码
我们看看 time 包源码中对 iota 关键字的使用:
......// A Month specifies a month of the year (January = 1, ...).type Month int
const ( January Month = 1 + iota February March April May June July August September October November December)......
复制代码
如果同一个 const 中定义了多个 iota 会怎样:
const ( i1 = iota i2
n1 = iota * 10 n2 n3)
func main() { fmt.Println(i1) fmt.Println(i2)
fmt.Println(n1) fmt.Println(n2) fmt.Println(n3)}
复制代码
打印结果:
好嘞,今天的分享就先到这里,欢迎大家关注我,会持续更新~
评论