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

8次阅读

共计 988 个字符,预计需要花费 3 分钟才能阅读完成。

咱们来看一段代码

你感觉 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
以上便是本期的全部内容

我是红豆,知易行难

咱们下期见

正文完
 0