Impresión de variables de estructura en Golang

Supongamos que necesitamos imprimir la estructura con el valor correspondiente de sus campos. Podemos hacer esto con la ayuda del paquete fmt que implementa E/S formateadas con funciones análogas a printf y scanf de C. Primero intentemos si solo imprimimos la estructura, qué sucederá.

package main
   
import ("fmt")
   
// Fields: structure to be printed
type Fields struct {
    Name     string
    NickName string
    Age      int
}
   
func main() {
  
    // Initialising the struct with values
    var f = Fields{
    Name:     "Abc",
    NickName: "abc",
    Age:      19,
    }
  
    // printing the structure
    fmt.Println(f)
}

Producción:

{Abc abc 19}

Hay dos formas de imprimir variables de estructura en Golang. La primera forma es usar la función Printf del paquete fmt con etiquetas especiales en los argumentos del formato de impresión. Algunos de esos argumentos son los siguientes:

%v the value in a default format
%+v the plus flag adds field names
%#v a Go-syntax representation of the value
package main
  
import (
    "fmt"
)
  
// Fields: structure to be printed
type Fields struct {
    Name     string
    NickName string
    Age      int
}
  
func main() {
  
    // initializing the 
    // struct with values
    var f = Fields{
        Name:     "Abc",
        NickName: "abc",
        Age:      19,
    }
      
    // printing the structure
    fmt.Printf("%v\n", f)
    fmt.Printf("%+v\n", f)
    fmt.Printf("%#v\n", f)
}

Producción:

{Abc abc 19}
{Name:Abc NickName:abc Age:19}
main.Fields{Name:"Abc", NickName:"abc", Age:19}

Printf con #v incluye main.Fields que es el nombre de la estructura. Incluye “principal” para distinguir la estructura presente en diferentes paquetes.

La segunda forma posible es usar la función Marshal de la codificación del paquete/json.

Sintaxis:

func Marshal(v interface{}) ([]byte, error)
package main
  
import (
    "encoding/json"
    "fmt"
)
  
// Fields: structure to be printed
type Fields struct {
    Name     string
    NickName string
    Age      int
}
  
func main() {
  
    // initialising the struct
    // with values
    var f = Fields{
        Name:     "Abc",
        NickName: "abc",
        Age:      19,
    }
      
    // Marshalling the structure
    // For now ignoring error
    // but you should handle
    // the error in above function
    jsonF, _ := json.Marshal(f)
  
    // typecasting byte array to string
    fmt.Println(string(jsonF))
  
}

Producción:

{"Name":"Abc", "NickName":"abc", "Age":19}

Publicación traducida automáticamente

Artículo escrito por manjeet_04 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 *