如何(在控制台中)在Golang中打印此结构的Id
、Title
、Name
等?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
发布于 2015-12-27 19:33:28
我想推荐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) ""
}
发布于 2018-07-11 00:24:49
我的2cents是使用json.MarshalIndent
--令人惊讶的是没有人建议这样做,因为它是最简单的。例如:
func prettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
没有外部的dep和结果,输出格式很好。
发布于 2017-03-29 16:53:50
如果您想要struct
的某种格式化输出,我认为实现自定义字符串会更好
例如
package main
import "fmt"
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
}
func (p Project) String() string {
return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name)
}
func main() {
o := Project{Id: 4, Name: "hello", Title: "world"}
fmt.Printf("%+v\n", o)
}
https://stackoverflow.com/questions/24512112
复制相似问题