Open In App

How to use Field Tags in the Definition of Struct Type in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

Golang provide structures for the definition of a custom datatype. The concept of structure in Go is similar to the structure in C/C++. Example:

type Person struct {
    Name    string
    Aadhaar   int
    Street  string
    HouseNo int
}

Structures in Golang can be written to files like JSON for storing data on a hard drive or for sending over the network. JSON is a lightweight data storage format. Go provides packages in the standard library to write structures to JSON file and retrieving structures from the JSON file. During the definition of structures, additional raw string values know as the field tags may be added to the field declaration which is used as the field name in JSON files. If no additional string value i.e field tag is specified, Go uses the default field name which is used to declare the field in the structure. Structure Definition with Field Tags:

type Person struct {
    Name    string `json:"name"`
    Aadhaar  int    `json: "aadhaar"`
    Street  string `json: "street"`
    HouseNo int    `json: "house_number"`
}

Note : Field name must start with a capital letter if you want to store structure in JSON. 

C




// Golang program to show how to use Field
// Tags in the Definition of Struct Type
package main
 
import (
    "encoding/json"
    "fmt"
)
 
type Person struct {
    Name    string `json:"name"`         // field tag for Name
    Aadhaar  int    `json:"aadhaar"`       // field tag for Aadhaar
    Street  string `json:"street"`       // field tag for Street
    HouseNo int    `json:"house_number"` // field tag for HouseNO
}
 
func main() {
 
    var p Person
 
    p.Name = "ABCD"
    p.Aadhaar = 1234123412341234
    p.Street = "XYZ"
    p.HouseNo = 10
 
    fmt.Println(p)
 
    // returns []byte which is p in JSON form.
    jsonStr, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err.Error())
    }
 
    fmt.Println(string(jsonStr))
 
    // Sample JSON data
    var str = `{
        "name" : "PQRX",
        "aadhaar" : 1234123412341234,
        "street" : "XYZW",
        "house_number" : 10
    }`
 
    var p2 Person
 
    // retains values of fields from JSON string
    err = json.Unmarshal([]byte(str), &p2)
    // and stores it into p2
    if err != nil {
        fmt.Println(err.Error())
    }
 
    fmt.Println(p2)
}


Output:

{ABCD 1234123412341234 XYZ 10}
{"name":"ABCD","aadhaar":1234123412341234,"street":"XYZ","house_number":10}
{PQRX 1234123412341234 XYZW 10}


Last Updated : 29 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads