我如何打印(到控制台)的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"`
}
当前回答
不使用外部库,每个字段后加新行:
log.Println(
strings.Replace(
fmt.Sprintf("%#v", post), ", ", "\n", -1))
其他回答
我建议使用json.Unmarshal() 我试着打印id,希望它有帮助:
var jsonString = `{"Id": 1, "Title": "the title", "Name": "the name","Data": "the data","Commits" : "the commits"}`
var jsonData = []byte(jsonString)
var data Project
var err = json.Unmarshal(jsonData, &data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Id :", data.Id)
我想推荐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) ""
}
访问这里查看完整的代码。在这里你还可以找到一个在线终端的链接,在那里可以运行完整的代码,程序表示如何提取结构的信息(字段的名称、类型和值)。下面是只打印字段名的程序片段。
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
*/
还有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