gostructgo-reflect

Read top level struct tags


How to get the tags from a struct field in Go? I have a nested struct which I want to pass as an argument to another function and read the tags there. I know that by accessing it as a field is possible, but I am searching for a way to it.

type MyStruct struct {
    Nested struct{} `bson:"nested"`
}

func main() {

    val := reflect.ValueOf(MyStruct{})
    val.Type().Field(0).Tag.Get("bson") // I want to avoid this
    
    val := reflect.ValueOf(MyStruct{}.Nested)
    val.Tag???
}

Solution

  • The tag you want to access belongs to MyStruct. If you pass the value of the Nested field, a copy is made which will be completely detached from MyStruct. There's no way to tell if the value passed originates from a field of MyStruct or from another struct, or from any other source (e.g. from a composite literal). So this is not possible.