我如何打印(到控制台)的Id,标题,名称等,这个结构在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"`
}

当前回答

还有go-render,它处理指针递归和字符串和int映射的大量键排序。

安装:

go get github.com/luci/go-render/render

例子:

type customType int
type testStruct struct {
        S string
        V *map[string]int
        I interface{}
}

a := testStruct{
        S: "hello",
        V: &map[string]int{"foo": 0, "bar": 1},
        I: customType(42),
}

fmt.Println("Render test:")
fmt.Printf("fmt.Printf:    %#v\n", a)))
fmt.Printf("render.Render: %s\n", Render(a))

打印:

fmt.Printf:    render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)}

其他回答

当你有更复杂的结构时,你可能需要在打印之前转换成JSON:

// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)

来源:https://gist.github.com/tetsuok/4942960

这些包中的大多数都依赖于reflect包来实现这些功能。

fmt.Sprintf()正在使用-> func (p *pp) printArg(参数接口{},动词符文)的标准库

转到第638行-> https://golang.org/src/fmt/print.go

反射:

https://golang.org/pkg/reflect/

示例代码:

https://github.com/donutloop/toolkit/blob/master/debugutil/prettysprint.go

fmt.Println("%+v", structure variable)

更好的方法是在名为“commons”(可能)的包中为字符串“%+v”创建一个全局常量,并在代码中处处使用它

//In commons package
const STRUCTURE_DATA_FMT = "%+v"

//In your code everywhere
fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)

如果您想写入日志文件,就像我之前搜索的那样。那么你应该使用:

log.Infof("Information %+v", structure)

注意::这将不适用于log。Info或log.Debug。在本例中,将打印“%v”,并且打印结构的所有值,而不打印键/变量名。

打印结构中字段的名称:

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

从fmt包:

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

假设你有一个项目的实例(在'yourProject'中)

文章JSON和Go将详细介绍如何从JSON结构中检索值。


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

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