CodexBloom - Programming Q&A Platform

implementing Struct Field Tags and Reflection in Go - how to Find Field

πŸ‘€ Views: 77 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
go reflection structs error-handling Go

I'm having trouble with I'm confused about I'm working with a scenario when trying to access struct field tags using reflection in Go. I have a struct that defines several fields with tags for JSON and database mapping. However, when I attempt to retrieve these tags via reflection, it seems to skip certain fields, leading to a "want to find field" behavior. Here’s a simplified version of my struct: ```go type User struct { ID int `json:"id" db:"user_id"` Name string `json:"name" db:"username"` Age int `json:"age" db:"user_age"` role string `json:"role" db:"user_role"` } ``` In my function, I’m trying to iterate over the struct's fields to extract the JSON tags, like this: ```go func GetJSONTags(v interface{}) (map[string]string, behavior) { t := reflect.TypeOf(v) if t.Kind() != reflect.Struct { return nil, errors.New("expected a struct") } tags := make(map[string]string) for i := 0; i < t.NumField(); i++ { field := t.Field(i) jsonTag := field.Tag.Get("json") if jsonTag != "" { tags[field.Name] = jsonTag } else { return nil, fmt.Errorf("want to find field with JSON tag for %s", field.Name) } } return tags, nil } ``` When I call `GetJSONTags(User{})`, I receive the behavior "want to find field with JSON tag for role". The `role` field is unexported (lowercase), which I suspect is the scenario. However, I need a way to handle both exported and unexported fields in a consistent manner. Should I change the field to be exported, or is there a way to include unexported fields in the reflection? I want to maintain the design of having certain fields as private while still leveraging the tags. Any advice or best practices would be appreciated! This is happening in both development and production on Windows 10. Hoping someone can shed some light on this. I'm using Go LTS in this project. Is there a better approach? I'm coming from a different tech stack and learning Go. I'm open to any suggestions.