关于golang:Go语言陷阱结构体未导出的字段无法被编解码

咱们来看一段代码

你感觉14、17、22行的输入别离是什么?

import (
  "encoding/json"
  "fmt"
)

type Data struct {
  One   int
  two   string
  three int
}

func main() {
  in := Data{1, "two", 3}
  fmt.Printf("%#v\n", in)

  encoded, _ := json.Marshal(in)
  fmt.Println(string(encoded))

  var out Data
  json.Unmarshal(encoded, &out)

  fmt.Printf("%#v\n", out)
}

定义构造体

type Data struct {
  One   int
  two   string
  three int
}

在构造中

英文大写字母结尾的属性是被导出的

而小写字母结尾的属性未导出的

因而

One 属性是被导出的

two、three是未导出的

编码

 ...
  in := Data{1, "two", 3}
  fmt.Printf("%#v\n", in) //prints main.MyData{One:1, two:"two", three:3}

  encoded, _ := json.Marshal(in)
  fmt.Println(string(encoded)) //prints {"One":1}
  ...

在上述2-3行代码,对Data数据结构申明并初始化

在第5行代码这里对构造体进行编码

第6行代码这里只输入了{“One”:1}也就是说 未被导出的字段是未被编码的

解码

  ...
  var out Data
  json.Unmarshal(encoded, &out)

  fmt.Printf("%#v\n", out) //prints main.MyData{One:1, two:"",three:0}
  ...

上述代码第3行对构造体进行解码

第5行代码输入{One:1, two:””,three:0}

未被带出的属性,解码是以零值(zero value)完结

总结

编码构造时,以小写字母结尾的struct属性不会被编码(json, xml, gob等)

解码构造时,未导出的字段中以零值(zero value)完结

注:bool的零值(初始值)为 false,int的零值为 0,string的零值为空字符串””

pointer、slice、map、channel、func和interface的零值则是 nil

END
以上便是本期的全部内容

我是红豆,知易行难

咱们下期见

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理