我如何打印(到控制台)的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"`
}
当前回答
我认为应该使用json。MarshalIndent——令人惊讶的是没有建议这样做,因为它是最直接的。例如:
func prettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
没有外部deps,结果输出格式很好。
其他回答
还有go-render,它处理指针递归和字符串和int映射的大量键排序。
安装:
go get github.com/luci/go-render/render
例子:
type customType int
type testStruct struct {
S string
V *map[string]int
I interface{}
}
a := testStruct{
S: "hello",
V: &map[string]int{"foo": 0, "bar": 1},
I: customType(42),
}
fmt.Println("Render test:")
fmt.Printf("fmt.Printf: %#v\n", a)))
fmt.Printf("render.Render: %s\n", Render(a))
打印:
fmt.Printf: render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)}
不使用外部库,每个字段后加新行:
log.Println(
strings.Replace(
fmt.Sprintf("%#v", post), ", ", "\n", -1))
当你有更复杂的结构时,你可能需要在打印之前转换成JSON:
// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)
来源:https://gist.github.com/tetsuok/4942960
我认为如果想要某种格式化的结构输出,最好实现自定义字符串
例如
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)
}
我认为应该使用json。MarshalIndent——令人惊讶的是没有建议这样做,因为它是最直接的。例如:
func prettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
没有外部deps,结果输出格式很好。