How to Define Multiple Name Tags in a Struct in Golang

To define multiple name tags in the Go struct, specify each tag inside the backticks (“) following the field type, separated by a space. Each tag usually consists of a key, a colon, and a value enclosed in double quotes. The key is typically the package’s name to process the tag, and the value is the custom information you want to associate with the field.

Example 1

Here’s an example of a struct with multiple tags for each field:

package main

import (
  "encoding/json"
  "fmt"
)

type Student struct {
  Name string `json:"name" xml:"Name" bson:"full_name"`
  Rollno int `json:"rollno" xml:"Rollno" bson:"rollno"`
  Location string `json:"location,omitempty" 
                   xml:"Location,omitempty" bson:"location,omitempty"`
}

func main() {
  student := Student{
    Name: "Krunal",
    Rollno: 21,
    Location: "Rajkot",
  }

  jsonData, err := json.Marshal(student)
  if err != nil {
    fmt.Println("Error marshaling to JSON:", err)
    return
  }

  fmt.Println("JSON output:", string(jsonData))
}

Output

JSON output: {"name":"Krunal","rollno":21,"location":"Rajkot"}

In this example, we define a Student struct with three fields: Name, Rollno, and Location. Each field has JSON, XML, and BSON serialization tags, including custom field names and optional omitempty directives.

When marshaling the Student struct to JSON, the encoding/json package will use the provided tags to create a JSON object with the specified field names.

Example 2

In Go, the struct type allows you to define a composite data type that groups variables of different data types. Each variable inside a struct is called a field.

You can also annotate these fields with tags. Tags are string literals associated with fields, mainly used for reflection.

package main

import (
  "fmt"
  "reflect"
)

type Person struct {
  Name string `json:"name" xml:"fullname"`
  Age int `json:"age" xml:"years"`
  Address string `json:"address,omitempty" xml:"address"`
}

func main() {
  t := reflect.TypeOf(Person{})
  for i := 0; i < t.NumField(); i++ {
    field := t.Field(i)
    fmt.Printf("Field: %s\n", field.Name)
    fmt.Printf("JSON tag: %s\n", field.Tag.Get("json"))
    fmt.Printf("XML tag: %s\n", field.Tag.Get("xml"))
    fmt.Println()
  }
}

Output

Define Multiple Name Tags in a Struct in Go

That’s it.