本文翻译自:How to print struct variables in console?
How can I print (in the console) the Id
, Title
, Name
, etc. of this struct in Golang? 如何在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楼
参考:https://stackoom.com/question/1eqie/如何在控制台中打印struct变量
#2楼
To print the name of the fields in a struct: 要在结构中打印字段的名称:
fmt.Printf("%+v\n", yourProject)
From the fmt
package : 来自fmt
包 :
when printing structs, the plus flag (
%+v
) adds field names 打印结构时,加号标志(%+v
)添加字段名称
That supposes you have an instance of Project (in ' yourProject
') 假设您有一个Project实例(在' yourProject
'中)
The article JSON and Go will give more details on how to retrieve the values from a JSON struct. 文章JSON和Go将提供有关如何从JSON结构中检索值的更多详细信息。
This Go by example page provides another technique: 这个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))
That would print: 那将打印:
{"page":1,"fruits":["apple","peach","pear"]}
If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example . 如果您没有任何实例,则需要使用反射来显示给定结构的字段名称, 如本例所示 。
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())
}
#3楼
I want to recommend go-spew , which according to their github "Implements a deep pretty printer for Go data structures to aid in debugging" 我想推荐go-spew ,根据他们的github“为Go数据结构实现深度漂亮的打印机以帮助调试”
go get -u github.com/davecgh/go-spew/spew
usage example: 用法示例:
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)
}
output: 输出:
(main.Project) {
Id: (int64) 0,
Title: (string) (len=5) "world",
Name: (string) (len=5) "hello",
Data: (string) "",
Commits: (string) ""
}
#4楼
There's also go-render , which handles pointer recursion and lots of key sorting for string and int maps. 还有go-render ,它处理指针递归和字符串和int映射的大量键排序。
Installation: 安装:
go get github.com/luci/go-render/render
Example: 例:
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))
Which prints: 哪个印刷品:
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)}
#5楼
Visit here to see the complete code. 访问此处查看完整代码。 Here you will also find a link for an online terminal where the complete code can be run and the program represents how to extract structure's information(field's name their type & value). 在这里,您还可以找到在线终端的链接,其中可以运行完整的代码,程序代表如何提取结构的信息(字段名称的类型和值)。 Below is the program snippet that only prints the field names. 以下是仅打印字段名称的程序片段。
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
*/
#6楼
I think it would be better to implement a custom stringer if you want some kind of formatted output of a struct
我认为如果你想要某种struct
的格式化输出,那么实现自定义stringer会更好
for example 例如
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)
}