Go Struct Tags
Struct tags are small strings of metadata attached to fields. They are used by other packages (like json, xml, or database drivers) to decide how to handle your data.
Syntax
Tags are placed in backticks after the type of a field.
How they work
The Go compiler ignores struct tags. However, other code can read them at runtime using Reflection.
Common Examples
- JSON:
json:"id,omitempty"(Change name, skip if empty). - Databases (GORM/SQL):
db:"user_id"(Map field to specific column name). - Validation:
validate:"required,email"(Used by libraries to check input data). - XML:
xml:"token,attr"(Map field to an XML attribute instead of a tag). e
Why use Struct Tags?
- Cleaner Code: You don't have to write manual conversion logic for every field.
- Flexibility: You can have one struct that maps to a JSON API, a PostgreSQL database, and an XML file, all with different field names.
- Declarative: You "describe" how the data should behave rather than writing the step-by-step logic.