Home >Backend Development >Golang >How Can I Pretty-Print Complex Data Structures in Go?
Printing complex data structures in Go can be challenging, especially when you want a representation that's both human-readable and well-indented. Ruby's awesome_print library offers an elegant solution for this task, and Go developers may wonder if there's an equivalent.
While there are several third-party libraries available for pretty printing, Go also provides a native solution using json.MarshalIndent. This function converts the Go data structure into a JSON representation and allows you to specify indentation.
x := map[string]interface{}{"a": 1, "b": 2} b, err := json.MarshalIndent(x, "", " ") if err != nil { fmt.Println("error:", err) } fmt.Print(string(b))
This code will produce the following output:
{ "a": 1, "b": 2 }
For advanced formatting needs, you can explore third-party libraries like:
The above is the detailed content of How Can I Pretty-Print Complex Data Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!