go - 为什么 Golang 不能从带有前小写字符的结构生成 json?

标签 go goroutine

我正在尝试从我创建的结构中打印 json 结果,如下所示:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}

打印出来

m:= &Machine{ m_ip:"test", m_type:"test", m_serial:"test" }
m_json:= json.Marshal(m)
fmt.Println(m_json)

但是,返回的结果只是 {}

其次,我尝试将单词的第一个字母更改为大写如下:

type Machine struct{
  MachIp string
  MachType string
  MachSerial string
}

它有效!为什么前面带小写字符的单词不管用?

最佳答案

Go 用例来确定特定标识符在包的上下文中是公共(public)的还是私有(private)的。在您的第一个示例中,这些字段对 json.Marshal 不可见,因为它不是包含您的代码的包的一部分。当您将字段更改为大写时,它们会变为公开的,因此可以导出。

如果您需要在 JSON 输出中使用小写标识符,您可以使用所需的标识符标记字段。例如:

type Machine struct{
    MachIp     string `json:"m_ip"`
    MachType   string `json:"m_type"`
    MachSerial string `json:"m_serial"`
}

关于go - 为什么 Golang 不能从带有前小写字符的结构生成 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21825322/

相关文章:

tensorflow - Golang Tensorflow 批量图像输入

go - 如何等待 goroutines 完成并在没有锁的情况下读取 channel ?

go - 关于golang channel 的一些问题

go - 同时计算树叶

go - 处理超时并收听 channel

go - 如何根据 goroutine 的返回值停止 goroutine

Go httputil.ReverseProxy 不覆盖 Host header

去眼镜蛇 : space separated values in StringArray flags

json - Marshall JSON slice 到有效的 JSON

go - 如何从解压缩文件中删除 gzip header 元数据