Open In App

Golang Program to Use Field Tags in the Definition of Struct Type

Improve
Improve
Like Article
Like
Save
Share
Report

Structure in Golang is used to store different types of data in one place. ‘struct’ itself is a user-defined data type. The syntax of ‘struct’ in Golang is as follow:

Syntax:

type var_name struct
{
     var1  data_type
     var2  data_type
}

Structure in Golang is written to files like JSON. It is a data storage format. Golang provides packages in the standard library to write and retrieve structures to/from the JSON file. In the definition of structures, field tags are added to the field declaration which is used as the field name in JSON files.

Syntax:

type Book struct 
{
    Name    string  `json:"name"`
    Author  string  `json: "author"`
    Price   int     `json: "price"`
}

Below programs illustrate the use of field tags in the definition of struct type in Golang:

Program 1:




// Golang program to show how to use
// field tags in the definition of Struct
package main
  
import 
(
    "encoding/json"
    "fmt"
)
  
type Book struct 
{
    Name    string  `json:"name"`
    Author  string  `json: "author"`
    Price   int     `json: "price"`
}
  
func main() {
  
    var b Book
  
    b.Name = "DBMS"
    b.Author = "Navathe"
    b.Price = 850
  
    fmt.Println(b)
  
    // returns []byte which is b in JSON form.
    jsonStr, err := json.Marshal(b)
    if err != nil {
        fmt.Println(err.Error())
    }
  
    fmt.Println(string(jsonStr))
}


Output:

{DBMS Navathe 850}
{"name":"DBMS", "author":"Navathe", "price":850}

Program 2:




// Golang program to show how to use
// field tags in the definition of Struct
package main
  
import 
(
    "encoding/json"
    "fmt"
)
  
type Fruit struct 
{
    Name    string  `json:"name"`
    Quantity  string  `json: "quantity"`
    Price   int     `json: "price"`
}
  
func main() {
  
    var f Fruit
  
    f.Name = "Apple"
    f.Quantity = "2KG"
    f.Price = 100
  
    fmt.Println(f)
  
    // returns []byte which is f in JSON form.
    jsonStr, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err.Error())
    }
  
    fmt.Println(string(jsonStr))
}


Output:

{Apple 2KG 100}
{"name":"Apple", "quantity":"2KG", "price":100}


Last Updated : 02 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads