衫裤跑路 2014-07-01 13:57 采纳率: 50%
浏览 517
已采纳

如何在控制台中打印结构变量?

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"`
}

转载于:https://stackoverflow.com/questions/24512112/how-to-print-struct-variables-in-console

  • 写回答

14条回答 默认 最新

  • 衫裤跑路 2014-07-01 14:00
    关注

    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())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入