为什么 Golang 无法从带有前面小写字符的结构生成 json? [英] Why Golang cannot generate json from struct with front lowercase character?

查看:28
本文介绍了为什么 Golang 无法从带有前面小写字符的结构生成 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to print json result from struct I created as following:

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)

然而,结果只返回了 {}

However, result returned just {}

其次,我尝试将单词的首字母改为大写,如下所示:

Secondly,I tried to changed the first letter of words to Uppercase as follow:

type Machine struct{
  MachIp string
  MachType string
  MachSerial string
}

它有效!无论如何,为什么前面带有小写字符的单词不起作用?

and it works! Why doesn't the word with lowercase character at the front work, anyway?

推荐答案

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

Go uses case to determine whether a particular identifier is public or private within the context of your package. In your first example, the fields are not visible to json.Marshal because it is not part of the package containing your code. When you changed the fields to be upper case, they became public so could be exported.

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

If you need to use lower case identifiers in your JSON output though, you can tag the fields with the desired identifiers. For example:

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

这篇关于为什么 Golang 无法从带有前面小写字符的结构生成 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆