衫裤跑路 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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?