我如何打印(到控制台)的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代码(相当于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",
}}

其他回答

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

不使用外部库,每个字段后加新行:

log.Println(
            strings.Replace(
                fmt.Sprintf("%#v", post), ", ", "\n", -1))

您可以先执行json mashal并将其作为字符串打印。你可以看到整个struct的值。

package main

import "fmt"
import "json"

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

func main() {
    o := Project{Id: 4, Name: "hello", Title: "world"}
    om, _ := json.marshal(o)
    log.Printf("%s\n", string(om))
}

我建议你使用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"}
fmt.Printf("%+v\n", project)

这是打印细节的基本方法