Go, how to print a struct?

Introduction

Sometimes it’s very useful to be able to display the contents of a variable.

On this page, you can find out how to display the contents of a structure in a variable, for example.

Beginner, using the fmt package

Go Playground

Use %+v in a fmt.Printf func.

theStructToPrint := struct {
	Name string
}{
	Name: "Julien",
}
fmt.Printf("%+v\n", theStructToPrint)

Output:

{Name:Julien}

Intermediary, using the json.Marshal func

Go Playground

Use json.Marshal func from encoding json package.

theStructToPrint := struct {
	Name string
}{
	Name: "Julien",
}
result, _ := json.Marshal(theStructToPrint)
fmt.Println(string(result))

Output:

{Name:Julien}

Advance, using the json.MarshalIndent func

Go Playground

Use json.MarshalIndent func from encoding json package.

theStructToPrint := struct {
	Name string
}{
	Name: "Julien",
}
result, _ := json.MarshalIndent(theStructToPrint, "", "\t")
fmt.Println(string(result))

Output:

{
	"Name": "Julien"
}

Because we only need to print the contents of a variable. We often avoid multiplying dependencies.

For example, you can use the package go-spew.

Playground

Get the package:

go get -u github.com/davecgh/go-spew/spew
theStructToPrint := struct {
	Name string
}{
	Name: "Julien",
}
spew.Dump(theStructToPrint)

Output:

(struct { Name string }) {
 Name: (string) (len=6) "Julien"
}