How to Create Tags in Go

Jay Singh Feb 02, 2024
  1. Create Tags Using the struct Function in Go
  2. Create Tags Using JSON in Go
How to Create Tags in Go

Structures, also known as structs, combine several data bits into a single entity. These data sets define higher-level notions like an address, consisting of a house number, street, city, state, and postal code.

You can use struct tags to regulate how this information is allocated to the fields of a struct when reading it from systems like databases or APIs. Struct tags are short bits of metadata connected to fields of a struct and offer instructions to other Go code that interacts with it.

This is a method of adding meta-data to your struct. The data can be utilized by your package or a third-party application to determine how to conduct a specific action or handle data appropriately.

This meta-data is separated by a space and declared using a string literal in the format key: value. Multiple tags exist in the same field, serving a distinct purpose and library.

This tutorial will demonstrate how to create tags using Go’s struct function.

Create Tags Using the struct Function in Go

A User type with a Name field is defined in this example. A struct tag of name has been added to the Name column.

Example 1:

package main

import "fmt"

type User struct {
	Name string `example:"name"`
}

func (u *User) String() string {
	return fmt.Sprintf("Hello, I am %s", u.Name)
}

func main() {
	u := &User{
		Name: "Jay Singh",
	}

	fmt.Println(u)
}

Output:

Hello, I am Jay Singh

You’ll need to use the reflect package to access and use the tags.

If the traditional format is utilized, we can use the Get and Lookup methods of StructTag to access information about the tag. The Lookup method also returns the value ok, indicating whether the tag was found in the field.

Example 2:

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name  string `color:"white"`
	Age   int    `color:"black"`
	Email string
}

func main() {
	a := User{"Jay", 99, "example@jay.com"}

	ut := reflect.TypeOf(a)
	for i := 0; i < ut.NumField(); i++ {
		field := ut.Field(i)
		if color, ok := field.Tag.Lookup("color"); ok {
			if color == "" {
				fmt.Println("(blank)")
			} else {
				fmt.Println(color)
			}
		} else {
			fmt.Println("(Not Specified)")
		}
	}
}

Output:

white
black
(Not Specified)

Create Tags Using JSON in Go

The standard library’s JSON encoder uses struct tags as annotations to tell the encoder how you want to name your fields in the JSON output. The encoding/json package contains these JSON encoding and decoding mechanisms.

To understand how JSON is encoded without struct tags, try this example:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"
)

type User struct {
	Name      string
	Password  string
	Address   []string
	CreatedAt time.Time
}

func main() {
	a := &User{
		Name:      "Jay Singh",
		Password:  "qwertyuiop",
		CreatedAt: time.Now(),
	}

	out, err := json.MarshalIndent(a, "", "  ")
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}

	fmt.Println(string(out))
}

Output:

{
    "Name": "Jay Singh",
    "Password": "qwertyuiop",
    "Address": null,
    "CreatedAt": "2022-03-10T23:00:00Z"
}