2020年9月8日 星期二

[ 常見問題 ] How to print struct variables in console?

 Source From Here

Question
How can I print (in the console) the Id, Title, Name, etc. of this struct in Golang?
  1. type Project struct {  
  2.     Id      int64   `json:"project_id"`  
  3.     Title   string  `json:"title"`  
  4.     Name    string  `json:"name"`  
  5.     Data    Data    `json:"data"`  
  6.     Commits Commits `json:"commits"`  
  7. }  
HowTo
To print the name of the fields in a struct:
  1. fmt.Printf("%+v\n", yourProject)  
From the fmt package:
when printing structs, the plus flag (%+v) adds field names

The article JSON and Go will give more details on how to retrieve the values from a JSON struct. This Go by example page provides another technique:
  1. type Response2 struct {  
  2.   Page   int      `json:"page"`  
  3.   Fruits []string `json:"fruits"`  
  4. }  
  5.   
  6. res2D := &Response2{  
  7.     Page:   1,  
  8.     Fruits: []string{"apple""peach""pear"}}  
  9. res2B, _ := json.Marshal(res2D)  
  10. 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:
  1. type T struct {  
  2.     A int  
  3.     B string  
  4. }  
  5.   
  6. t := T{23"skidoo"}  
  7. s := reflect.ValueOf(&t).Elem()  
  8. typeOfT := s.Type()  
  9.   
  10. for i := 0; i < s.NumField(); i++ {  
  11.     f := s.Field(i)  
  12.     fmt.Printf("%d: %s %s = %v\n", i,  
  13.         typeOfT.Field(i).Name, f.Type(), f.Interface())  
  14. }  

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...