Home >Backend Development >Golang >How Do I Control Which Struct Fields Are Exported in Go?
When using structs to represent data in Go, it's important to consider the capitalization of field names. By convention, only fields starting with a capital letter are exported, making them visible outside the current package.
In the provided code, the Person struct has a field named Age with a capital letter, while name is lowercase. As a result, only the Age field is exported when the struct is passed to the CouchDB library's PostDocument method.
The same principle applies when marshaling JSON using the json package. Only exported fields (starting with a capital letter) will be included in the output. This behavior is described in the Go language specification: http://golang.org/ref/spec#Exported_identifiers.
To include lowercase fields in the database or JSON output, use "tags" in the struct definition. For example:
type Sample struct { Name string `json:"name"` Age int `json:"age"` }
The tags provide an explicit mapping between the exported field names (Name and Age) and their lowercase equivalents (name and age).
By using tags or following the convention of using uppercase field names for exported fields, you can ensure that all fields in your structs are handled correctly when interacting with third-party libraries or performing JSON operations.
The above is the detailed content of How Do I Control Which Struct Fields Are Exported in Go?. For more information, please follow other related articles on the PHP Chinese website!