我如何打印(到控制台)的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"`
}

当前回答

我推荐使用Pretty Printer Library。这样你可以很容易地打印任何结构体。

安装库 https://github.com/kr/pretty

or

go get github.com/kr/pretty

现在在代码中这样做

package main

import (
fmt
github.com/kr/pretty
)

func main(){

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

fmt.Printf("%# v", pretty.Formatter(Project)) //It will print all struct details

fmt.Printf("%# v", pretty.Formatter(Project.Id)) //It will print component one by one.

}

此外,您还可以通过这个库获取组件之间的差异等等。你也可以在这里查看图书馆文档。

其他回答

打印JSON格式的结构体:

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

也可以用(如上所述):

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

但是第二个选项打印不带""的字符串值,因此更难读取。

当你有更复杂的结构时,你可能需要在打印之前转换成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。Printf("%#v\n", s),它将打印golang类型在同一时间

package main

import (
    "fmt"
    "testing"
)

type student struct {
    id   int32
    name string
}

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

func TestPrint(t *testing.T) {
    s := Project{1, "title","jack"}
    fmt.Printf("%+v\n", s)
    fmt.Printf("%#v\n", s)
}

结果:

{Id:1 Title:title Name:jack}
main.Project{Id:1, Title:"title", Name:"jack"}

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

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

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