Detail Go struct formatted output

  • 2020-11-03 22:29:29
  • OfStack

In the case of locating problems in the software system, the log is indispensable. However, when a system has many functions and many logs need to be printed, the output format that is easy to read is indispensable in order to improve the efficiency of browsing the log.

Printing a structure is the most common operation when printing a log, but it is not easy to read when more of the structure is in line 1. In Go, the structure can be easily converted to JSON, so we can use JSON to complete the formatted output of struct.

Print on line 1, using %+v to display the structure field name:


package main

import (
	"fmt"
)

// Student  Student information 
type Student struct {
	Name  string
	Addr  HomeInfo
	M   map[string]string
}

// HomeInfo  Home address 
type HomeInfo struct {
	Province   string
	City     string
	County    string
	Street    string
	DetailedAddr string
}

var student = Student{
	Name: "dablelv",
	Addr: HomeInfo{
		Province:   "Guangdong",
		City:     "Shenzhen",
		County:    "Baoan",
		Street:    "Xixiang",
		DetailedAddr: "Shengtianqi",
	},
	M: map[string]string{
		"hobby": "pingpopng",
	},
}

func main() {
	fmt.Printf("student=%+v\n", student)
}

Operation output:

[

student={Name:cat Addr:{Province:Guangdong City:Shenzhen County:Baoan Street:Xixiang DetailedAddr:Shengtianqi} M:map[hobby:pingpopng]}

]

Output formatted JSON string:


func main() {
	bs, _ := json.Marshal(student)
	var out bytes.Buffer
	json.Indent(&out, bs, "", "\t")
	fmt.Printf("student=%v\n", out.String())
}

Operation output results:

[

student={
"Name": "cat",
"Addr": {
"Province": "Guangdong",
"City": "Shenzhen",
"County": "Baoan",
"Street": "Xixiang",
"DetailedAddr": "Shengtianqi"
},
"M": {
"hobby": "pingpopng"
}
}

]

Formatting the output after converting strutc to json string greatly increases readability.

The conversion function has been added to your personal Go tool library, go-ES61en-ES62en, using the following example:


package main

import (
	"fmt"
  huge "github.com/dablelv/go-huge-util"
)

func main() {
	s, _ := huge.ToFormattedJSON(&student)
	fmt.Printf("student=%v\n", s)
}

Operation output:

[

student={
"Name": "cat",
"Addr": {
"Province": "Guangdong",
"City": "Shenzhen",
"County": "Baoan",
"Street": "Xixiang",
"DetailedAddr": "Shengtianqi"
},
"M": {
"hobby": "pingpopng"
}
}

]

The above is a detailed explanation of the Go structure formatted output content, more information about Go structure formatted output please pay attention to other related articles on this site!


Related articles: