1

I do not understand how field tags in struct are used and when. Per https://golang.org/ref/spec#Struct_types:

[tag] becomes an attribute for all the fields in the corresponding field declaration

what does this mean?

1

1 Answer 1

1

[tag] becomes an attribute for all the fields in the corresponding field declaration

In addition to the links above ("What are the use(s) for tags in Go?", "go lang, struct: what is the third parameter") this thread provides an example which does not come from the standard packages:

Suppose I have the following code (see below). I use a type switch the check the type of the argument in WhichOne().

How do I access the tag ("blah" in both cases)?
I'm I forced the use the reflection package, or can this also be done in "pure" Go?

type PersonAge struct {
        name string "blah"
        age  int
}

type PersonShoe struct {
        name     string "blah"
        shoesize int
}

func WhichOne(x interface{}) {
    ...
}

After reading that (again), looking in json/encode.go and some trial and error, I have found a solution.
To print out "blah" of the following structure:

type PersonAge struct {
        name string "blah"
        age  int
}

You'll need:

func WhichOne(i interface{}) {
        switch t := reflect.NewValue(i).(type) {
        case *reflect.PtrValue:
                x := t.Elem().Type().(*reflect.StructType).Field(0).Tag
                println(x)
        }  
}

Here: Field(0).Tag illustrates the "becomes an attribute for all the fields in the corresponding field declaration".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.