DEV Community

Ankit malik
Ankit malik

Posted on

How to create and read custom tags in Golang

Go (often referred to as Golang) is a statically typed, compiled language that has gained immense popularity in recent years due to its simplicity and efficiency. One of its standout features is the ability to use custom struct tags, which allow you to attach metadata to struct fields. Custom tags are commonly used for tasks such as data validation, serialization, and database mapping. In this article, we will explore how to create and read custom tags in Go.

Understanding Struct Tags

Struct tags in Go are string literals that can be associated with struct fields. These tags are used to convey metadata about the field to the Go runtime. Struct tags are typically used to provide information to external packages or to guide the behavior of your code.

The general format of a struct tag is as follows:

type MyStruct struct {
    FieldName FieldType `tag:"value"`
Enter fullscreen mode Exit fullscreen mode

Here, tag is the key, and "value" is the actual value of the tag. The content and structure of the tag value are entirely up to you, and you can define your custom tags as needed.

Creating Custom Tags

Let's create a simple example to demonstrate how to create custom tags in Go. Suppose you're building a web application and need to validate user input. You can use custom tags to specify validation rules for different fields in a struct.

package main

import (

type User struct {
    Username string `ankit:"required,min=5,max=20"`
    Email    string `ankit:"required,email"`
    Test     string

func main() {
    user := User{
        Username: "john_doe",
        Email:    "",
        Test:     "test value",


func validateStruct(data interface{}) {
    val := reflect.ValueOf(data)
    for i := 0; i < val.NumField(); i++ {
        tag := val.Type().Field(i).Tag.Get("ankit")
        fmt.Printf("Field: %s, Tag: %s\n", val.Type().Field(i).Name, tag)
        // Implement your validation logic here based on the tag value.

Enter fullscreen mode Exit fullscreen mode


Image description

link to on go-playground:

In this example, we've defined a User struct with custom tags validate on the Username and Email fields. The validateStruct function uses reflection to inspect the struct and extract the tags. You can then implement validation logic based on the tags, ensuring that the Username is required and has a length between 5 and 20 characters, and that the Email is required and in a valid email format.

Reading Custom Tags
Once you've attached custom tags to your struct fields, you can use reflection to read and interpret these tags. In the example above, the validateStruct function retrieves the custom tags and prints them. In a real application, you would use the tag values to perform specific actions or validations.

Best Practices

While custom struct tags in Go offer great flexibility, it's important to follow some best practices:

  • Use Descriptive Tag Names: Choose tag names that are descriptive and convey their purpose clearly. This makes your code more readable and maintainable.
  • Document Tags: Document the purpose and expected format of your custom tags in your code or documentation. This helps other developers understand how to use your structs effectively.
  • Validation Logic Separation: Separation of concerns is crucial. Avoid putting complex logic directly in your tag parsing code. Instead, parse the tags and use the information to trigger appropriate validation functions or other actions.
  • Avoid Overuse: Custom struct tags are a powerful tool, but they should be used judiciously. Avoid adding tags to every field in your struct; only use them when they provide clear benefits.
  • Error Handling: Implement error handling in your tag parsing and validation code. Handle scenarios where tags are missing or incorrectly formatted gracefully.


Custom struct tags in Go provide a flexible way to attach metadata to struct fields, allowing you to add valuable information to your code. Whether you're building web applications, handling data serialization, or working with databases, custom tags can simplify complex tasks and make your code more efficient. By following best practices and understanding how to create and read custom tags, you can harness the power of Go's reflection capabilities and write cleaner, more maintainable code.

Top comments (0)