Golang Program to Use Field Tags in the Definition of Struct Type
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:
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)
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:
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)
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
Share your thoughts in the comments
Please Login to comment...