How to Print Struct Values in Go
Printing struct values is a common requirement for debugging in Go. Using the
straightforward fmt.Println()
method outputs the struct’s values without the
names of its fields, as shown in the following example:
package main
import (
"fmt"
)
type Person struct {
name string
age int
email string
}
func main() {
p := Person{
name: "Drake",
age: 35,
email: "drake@example.com",
}
fmt.Println(p)
}
{Drake 35 drake@example.com}
For a more descriptive output that includes field names, the %+v
format
specifier with fmt.Printf()
is useful:
func main() {
p := Person{
name: "Drake",
age: 35,
email: "drake@example.com",
}
fmt.Printf("%+v\n", p)
}
{name:Drake age:35 email:drake@example.com}
For beautifully formatted and indented JSON output that includes only exported
fields, json.MarshalIndent()
from the standard library can also be used:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Email string
}
func main() {
p := Person{
Name: "Drake",
Age: 35,
Email: "drake@example.com",
}
// Indent with the tab character `\t`
// You can replace `\t` with " " if you want space indenting instead
str, _ := json.MarshalIndent(p, "", "\t")
fmt.Println(string(str))
}
{
"Name": "Drake",
"Age": 35,
"Email": "drake@example.com"
}
Third-party libraries
For scenarios where the standard library does not meet your requirements, consider exploring third-party libraries like litter or go-spew for advanced struct printing capabilities.
package main
import (
"github.com/davecgh/go-spew/spew"
)
type Person struct {
Name string
Age int
Email string
}
func main() {
p := Person{
Name: "Drake",
Age: 35,
Email: "drake@example.com",
}
spew.Dump(p)
}
(main.Person) {
Name: (string) (len=5) "Drake",
Age: (int) 35,
Email: (string) (len=17) "drake@example.com"
}
Thanks for reading, and happy coding!