如何在控制台中打印结构变量? [英] How to print struct variables in console?

查看:164
本文介绍了如何在控制台中打印结构变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打印(在控制台中) Id 标题名称



 类型项目结构{
Id int64 `json:project_id`
标题字符串`json:title`
名称字符串`json:name`
数据数据`json:data`
Commits Commits`json:commitits`
}


解决方案


$ b

  fmt.Printf(%+ v \ n)打印结构中字段的名称

,yourProject)

fmt 软件包


打印结构时,加标志(%+ v )添加字段名称


假设你有Project的一个实例(在' yourProject '中)

文章 JSON和Go 将提供更多详细信息关于如何从JSON结构中获取值。






这个按示例页面提供了另一种技术:

 类型Response2结构{
Page int `json:page`
Fruits [] string`json:fruits`
}

res2D:=& Response2 {
Page:1,
Fruits:[] string {apple,peach,pear}}
res2B,_:= json.Marshal(res2D)
fmt.Println(string(res2B) )

打印:

  {Page:1,Fruits:[apple,peach,pear]} 






如果您没有任何实例,那么您需要 使用反射 显示给定结构的字段名称,

  type T struct {
A int
B条g


t:= T {23,skidoo}
s:= reflect.ValueOf(& t).Elem()
typeOfT:= s .Type()

for i:= 0;我< s.NumField(); i ++ {
f:= s.Field(i)
fmt.Printf(%d:%s%s =%v \ n,i,
typeOfT.Field(i) .Name,f.Type(),f.Interface())
}


How can I print (in the console) the Id, Title, Name, etc. of this struct in Golang?

type Project struct {
    Id int64 `json:"project_id"`
    Title string `json:"title"`
    Name string `json:"name"`
    Data Data `json:"data"`
    Commits Commits `json:"commits"`
}

To print the name of the fields in a struct:

fmt.Printf("%+v\n", yourProject)

From the fmt package:

when printing structs, the plus flag (%+v) adds field names

That supposes you have an instance of Project (in 'yourProject')

The article JSON and Go will give more details on how to retrieve the values from a JSON struct.


This Go by example page provides another technique:

type Response2 struct {
  Page   int      `json:"page"`
  Fruits []string `json:"fruits"`
}

res2D := &Response2{
    Page:   1,
    Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))

That would print:

{"Page":1,"Fruits":["apple","peach","pear"]}


If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.

type T struct {
    A int
    B string
}

t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()

for i := 0; i < s.NumField(); i++ {
    f := s.Field(i)
    fmt.Printf("%d: %s %s = %v\n", i,
        typeOfT.Field(i).Name, f.Type(), f.Interface())
}

这篇关于如何在控制台中打印结构变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆