How to Define Multiple Name Tags in a Struct in Golang

To define multiple name tags in the Golang struct, you can 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.

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.

That’s it.

Leave a Comment