打印结构体字段的名称:
fmt.Printf("%+v\n", yourProject)
从
fmt
包 中得知:
在打印结构体时,加号标志(
%+v
)会添加字段名。
这假设你有一个 Project 的实例(在 '
yourProject
' 中)。
文章
JSON and Go 将详细介绍如何从 JSON 结构中检索值。
这个
Go by example 页面 提供了另一种技术:
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
这将会输出:
{"page":1,"fruits":["apple","peach","pear"]}
如果您没有任何实例,那么您需要使用反射来显示给定结构体的字段名称,就像这个例子一样。
要了解更多有关反射的信息,请参阅这篇文章。
type T struct {
A int
B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
fmt.Println
。 - Ry-