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

其他回答

非常简单的 我没有数据和提交的结构,所以我改变了

package main

import (
    "fmt"
)

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() {
    p := Project{
    1,
    "First",
    "Ankit",
    "your data",
    "Commit message",
    }
    fmt.Println(p)
}

关于学习,你可以从这里获得帮助:https://gobyexample.com/structs

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

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

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

打印JSON格式的结构体:

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

也可以用(如上所述):

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

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

这些包中的大多数都依赖于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

另一种方法是,创建一个名为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())
}