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:

Get hands-on with 1200+ tech skills courses.