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

新手上路,请多包涵

我如何打印(到控制台) Id , Title , Name 结构等?

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

原文由 fnr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 549
2 个回答

要打印结构中字段的名称:

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

来自 fmt

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

假设您有一个项目实例(在“ yourProject ”中)

文章 JSON and Go 将提供有关如何从 JSON 结构检索值的更多详细信息。


这个 Go by example 页面 提供了另一种技术:

 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))

那会打印:

 {"page":1,"fruits":["apple","peach","pear"]}


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

 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())
}

原文由 VonC 发布,翻译遵循 CC BY-SA 4.0 许可协议

我想推荐 go-spew ,根据他们的 github “为 Go 数据结构实现一个深度漂亮的打印机以帮助调试”

 go get -u github.com/davecgh/go-spew/spew

使用示例:

 package main

import (
    "github.com/davecgh/go-spew/spew"
)

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

func main() {

    o := Project{Name: "hello", Title: "world"}
    spew.Dump(o)
}

输出:

 (main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}

原文由 Martin Olika 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏