我如何打印(到控制台)的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"`
}
我如何打印(到控制台)的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"`
}
当前回答
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type
其他回答
我想推荐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) ""
}
我建议你使用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"}
我推荐使用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.
}
此外,您还可以通过这个库获取组件之间的差异等等。你也可以在这里查看图书馆文档。
或者,尝试使用这个函数PrettyPrint()
// print the contents of the obj
func PrettyPrint(data interface{}) {
var p []byte
// var err := error
p, err := json.MarshalIndent(data, "", "\t")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s \n", p)
}
为了使用这个,除了fmt和encoding/json之外,你不需要任何额外的包,只需要一个引用、指针或你所创建的结构的文字。
为了使用你的结构,初始化它在main或任何包中,并将它传递给PrettyPrint()。
type Prefix struct {
Network string
Mask int
}
func valueStruct() {
// struct as a value
var nw Prefix
nw.Network = "10.1.1.0"
nw.Mask = 24
fmt.Println("### struct as a pointer ###")
PrettyPrint(&nw)
}
它的输出是
### struct as a pointer ###
{
"Network": "10.1.1.0",
"Mask": 24
}
摆弄一下这里的代码。
fmt.Printf("%+v\n", project)
这是打印细节的基本方法