from.. 2014-07-01 13:57 采纳率: 100%
浏览 368
已采纳

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

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条回答 默认 最新

  • local-host 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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示