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
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
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
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"
}
Not recommended, using an external package
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
.
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"
}