Structs with Tags
In this lesson, we'll cover how to attach a tag with the field of a struct and how to read it.
We'll cover the following...
A field in a struct can, apart from a name and a type, also optionally have a tag. It is a string (or a raw string) attached to the field, which could be documentation or some other important label. The tag-content cannot be used in normal programming; only the package reflect
can access it. This package which we’ll explore deeper in the next chapter (Chapter 9), can investigate types, their properties, and methods in runtime. For example:
reflect.TypeOf()
on a variable gives its type. If this is a struct type, it can be indexed by Field
, and then, the Tag
property can be used.
The following program shows how this works:
package mainimport ("fmt""reflect")type TagType struct { // tagsfield1 bool "An important answer"field2 string `The name of the thing`field3 int "How much there are"}func main() {tt := TagType{true, "Barack Obama", 1}for i:= 0; i < 3; i++ {refTag(tt, i)}}func refTag(tt TagType, ix int) {ttType := reflect.TypeOf(tt)ixField := ttType.Field(ix) // getting field at a position ixfmt.Printf("%v\n", ixField.Tag) // printing tags}
In the above code, at line 4, we import a package reflect
. At line 7, we are making a struct TagType
type variable with three ...