Junior — Middle
Share your experience of using custom tags when creating data structures.
sobes.tech AI
Answer from AI
In Go, custom tags (struct tags) are used to add metadata to struct fields, which can be utilized during serialization, validation, database operations, and other tasks.
Experience with custom tags typically includes:
- Defining tags to control library behavior, for example,
json:"field_name"to specify the field name during JSON serialization. - Creating custom tags for specific logic, such as
validate:"required,min=3"to describe validation rules. - Using reflection (
reflect) to read tags and dynamically alter program behavior.
Example of a custom tag and reading it via reflection:
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string `custom:"required"`
Email string `custom:"optional"`
}
func main() {
u := User{Name: "Alice", Email: "alice@example.com"}
t := reflect.TypeOf(u)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get("custom")
fmt.Printf("Field: %s, Custom tag: %s\n", field.Name, tag)
}
}
This approach allows creating flexible and extensible data structures with additional information useful for various tools and libraries.