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"`
}
ベストアンサー1
構造体内のフィールド名を印刷するには:
fmt.Printf("%+v\n", yourProject)
からfmt
パッケージ:
構造体を印刷する場合、プラスフラグ(
%+v
)はフィールド名を追加します
これは、Project のインスタンス (' yourProject
' 内)があることを前提としています。
記事JSON と GoJSON 構造体から値を取得する方法について詳しく説明します。
これサンプルページから進む別のテクニックを提供します:
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())
}