An example of a struct in the Go program is provided below:
id int
name string
age int
}
The previous example shows an explicit struct where the fields belong to that specific struct.
You can also declare an implicit struct where the fields are declared in another struct. These are also known as embedded structs.
An example is shown below:
id int
name string
age int
}
type Developer struct {
User
salary int
}
In this previous example, the Developer struct accesses the fields of the User struct.
Struct Tags
In the Go programs, you can add an optional string literal to a struct field. This is known as a struct tag. It is used to hold meta-information for a struct field. You can then export the information in the field to other packages to execute an operation or structure the data appropriately.
You will often find tags in encoding packages, such as XML, JSON, YAML, ORMs, and Config management.
To declare a tag for a struct field, you can pass the key-value pair inside string literal braces as “key:value”. To add more than one tag, separate each tag using a space.
Here’s the following example:
id int
name string `max:"10"`
age int ``
}
Struct Tags and Reflect Package
To access and use struct tags, you will need the reflect package. It is part of the Go standard library, and you can import it with the clause:
It provides the Get and LookUp methods to work with tags.
To check if the tag is found within a field, we can use the LookUp method. An example code is provided below:
import (
"fmt"
"reflect"
)
type User struct {
id int
name string `max:"10"`
age int ``
}
func main() {
u := User{1, "Jane Doe", 34}
t := reflect.TypeOf(u)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if _, ok := f.Tag.Lookup("max"); ok {
fmt.Println("Tag found")
}else {
fmt.Println("Tag not found")
}
}
}
The previous code example will loop over the fields of the struct and check if the specified tag is found in the field.
To get the field with the specified tag, we can do the following:
import (
"fmt"
"reflect"
)
type User struct {
id int
name string `max:"10"`
age int ``
}
func main() {
u := User{1, "Jane Doe", 34}
t := reflect.TypeOf(u)
for i := 0; i < t.NumField(); i++ {
fmt.Println(t.Field(i).Name)
fmt.Println(t.Field(i).Tag.Get("max"))
}
}
Conclusion
This article covers the fundamentals of working and using struct tags and the reflect package. In addition, the definition and nature of structs were discussed. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.