Programa Golang para usar etiquetas de campo en la definición de tipo de estructura

La estructura en Golang se usa para almacenar diferentes tipos de datos en un solo lugar. ‘struct’ en sí mismo es un tipo de datos definido por el usuario. La sintaxis de ‘struct’ en Golang es la siguiente:

Sintaxis:

type var_name struct
{
     var1  data_type
     var2  data_type
}

La estructura en Golang se escribe en archivos como JSON. Es un formato de almacenamiento de datos. Golang proporciona paquetes en la biblioteca estándar para escribir y recuperar estructuras hacia/desde el archivo JSON. En la definición de estructuras, las etiquetas de campo se agregan a la declaración de campo que se utiliza como nombre de campo en los archivos JSON.

Sintaxis:

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

Los siguientes programas ilustran el uso de etiquetas de campo en la definición del tipo de estructura en Golang:

Programa 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))
}

Producción:

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

Programa 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))
}

Producción:

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

Publicación traducida automáticamente

Artículo escrito por pp_pankaj y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *