我如何打印(到控制台)的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"`
}
当前回答
我想推荐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))
我推荐使用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.
}
此外,您还可以通过这个库获取组件之间的差异等等。你也可以在这里查看图书馆文档。
访问这里查看完整的代码。在这里你还可以找到一个在线终端的链接,在那里可以运行完整的代码,程序表示如何提取结构的信息(字段的名称、类型和值)。下面是只打印字段名的程序片段。
package main
import "fmt"
import "reflect"
func main() {
type Book struct {
Id int
Name string
Title string
}
book := Book{1, "Let us C", "Enjoy programming with practice"}
e := reflect.ValueOf(&book).Elem()
for i := 0; i < e.NumField(); i++ {
fieldName := e.Type().Field(i).Name
fmt.Printf("%v\n", fieldName)
}
}
/*
Id
Name
Title
*/
您可以先执行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))
}
这些包中的大多数都依赖于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