📜  在 Golang 的控制台中打印结构变量

📅  最后修改于: 2021-10-24 13:35:38             🧑  作者: Mango

Golang 中的结构体或结构体是用户定义的类型,它允许将可能不同类型的项目分组/组合成单个类型。任何具有某些属性/字段集的现实世界实体都可以表示为一个结构体。这个概念通常与面向对象编程中的类进行比较。它可以称为不支持继承但支持组合的轻量级类。有两种方法可以在控制台打印结构体变量,如下所示:

1.使用带有以下标签的Printf函数

例子:

// Golang program to show how to print
// the struct variables in console
package main
  
// importing package for printing
import (
    "fmt"
)
  
// taking a struct
type emp struct {
    name   string
    emp_id int
    salary int
}
  
func main() {
  
    // an instance of emp (in 'e')
    e := emp{"GFG", 134, 30000}
  
    // printing with variable name
    fmt.Printf("%+v", e)
  
    fmt.Println()
      
    // printing without variable name
    fmt.Printf("%v", e)
}

输出:

{name:GFG emp_id:134 salary:30000}
{GFG 134 30000}

2.使用包 encoding/json 的 Marshal 打印。

例子:

// Golang program to show how to print
// the struct variables in console
package main
  
import ( 
    "encoding/json"
    "fmt"
) 
  
// taking a struct
type emp struct {
    Name   string
    Emp_id string
    Salary int
}
  
func main() {
  
    // an instance of emp (in 'e')
    var e = emp{ 
        Name:     "GFG", 
        Emp_id:   "123", 
        Salary:    78979854 , 
    } 
  
    // Marshalling the structure
    // For now ignoring error
    // but you should handle
    // the error in above function
    jsonF, _ := json.Marshal(e)
  
    // typecasting byte array to string
    fmt.Println(string(jsonF))
}

输出:

{"Name":"GFG","Emp_id":"123","Salary":78979854}