Home >Backend Development >Golang >How Do I Control Which Struct Fields Are Exported in Go?

How Do I Control Which Struct Fields Are Exported in Go?

DDD
DDDOriginal
2024-12-01 00:34:11231browse

How Do I Control Which Struct Fields Are Exported in Go?

Exporting Struct Fields 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.

CouchDB Struct Issue

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.

Marshaling and Field Visibility

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.

Overcoming Field Invisibility

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn