douque9815 2014-07-01 13:57
浏览 217
已采纳

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

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"`
}
  • 写回答

14条回答 默认 最新

  • duanpo7282 2014-07-01 14:00
    关注

    To print the name of the fields in a struct:

    fmt.Printf("%+v
    ", 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
    ", i,
            typeOfT.Field(i).Name, f.Type(), f.Interface())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝