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

当前回答

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

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

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

其他回答

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)

我想推荐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) ""
}

另一种方法是,创建一个名为toString的func,它接受struct,格式化 如你所愿。

import (
    "fmt"
)

type T struct {
    x, y string
}

func (r T) toString() string {
    return "Formate as u need :" + r.x + r.y
}

func main() {
    r1 := T{"csa", "ac"}
    fmt.Println("toStringed : ", r1.toString())
}

有时,将结构体打印为有效的Go代码(相当于Go /ast代码)可能会很方便。出于这个目的,https://github.com/hexops/valast做得很好:

package main

import (
    "fmt"

    "github.com/hexops/valast"
)

type ProjectData struct {
    Title   string `json:"title"`
    Name    string `json:"name"`
    Data    string `json:"data"`
    Commits string `json:"commits"`
}

type Project struct {
    Id   int64        `json:"project_id"`
    Data *ProjectData `json:"data"`
}

func main() {
    p := Project{
        Id: 1,
        Data: &ProjectData{
            Title:   "Test",
            Name:    "Mihai",
            Data:    "Some data",
            Commits: "Test Message",
        },
    }
    fmt.Println(valast.String(p))
}

输出:

go run main.go 
Project{Id: 1, Data: &ProjectData{
        Title:   "Test",
        Name:    "Mihai",
        Data:    "Some data",
        Commits: "Test Message",
}}

打印JSON格式的结构体:

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

也可以用(如上所述):

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

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