我如何打印(到控制台)的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 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))
}
其他回答
还有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)}
当你有更复杂的结构时,你可能需要在打印之前转换成JSON:
// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)
来源:https://gist.github.com/tetsuok/4942960
如果您想写入日志文件,就像我之前搜索的那样。那么你应该使用:
log.Infof("Information %+v", structure)
注意::这将不适用于log。Info或log.Debug。在本例中,将打印“%v”,并且打印结构的所有值,而不打印键/变量名。
不使用外部库,每个字段后加新行:
log.Println(
strings.Replace(
fmt.Sprintf("%#v", post), ", ", "\n", -1))
非常简单的 我没有数据和提交的结构,所以我改变了
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