How to print struct values in Go

The article describes various methods for printing struct values using standard library methods and also lists some third-party options at the end

It’s often necessary to print out struct values to the console for the purpose of debugging. If you use the go-to fmt.Println method, it only prints the values of the struct without the field names.

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)
}
output
{Drake 35 drake@example.com}

To include the field names in the output, you can use the %+v verb along with fmt.Printf:

func main() {
	p := Person{
		name:  "Drake",
		age:   35,
		email: "drake@example.com",
	}
	fmt.Printf("%+v\n", p)
}
output
{name:Drake age:35 email:drake@example.com}

Another option is to use json.MarshalIndent which is also part of the standard library. It gives a nicely formatted output according to the provided intendation. Note that this method only prints exported struct fields.

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))
}
output
{
        "Name": "Drake",
        "Age": 35,
        "Email": "drake@example.com"
}

If the above standard library solutions does not suit your purpose, you can try third-party packages such as litter or go-spew.

Thanks for reading, and happy coding!