Why Golang cannot generate json from struct with front lowercase character?

StackOverflow https://stackoverflow.com/questions/21825322

  •  12-10-2022
  •  | 
  •  

문제

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
}

and print out

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 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.

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"`
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top