Standard fmt.Print()
does not print variable names of Go structs, but it does not mean you cannot do that. To print struct variables in Go, you can use the following methods:
- Use
fmt.Printf()
with format “verbs”%+v
or%#v
. - Convert the struct to JSON and print the output.
- Use external packages to pretty-print structs, for example,
go-spew
.
See the example below and compare these three options.
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/davecgh/go-spew/spew"
)
type Fruit struct {
Name string
color string
Similar *Fruit
}
func main() {
strawberry := Fruit{
Name: "strawberry",
color: "red",
Similar: nil,
}
raspberry := Fruit{
Name: "raspberry",
color: "pink",
Similar: &strawberry,
}
// fmt.Printf with format verbs
fmt.Printf("fmt.Printf with format verbs\n")
fmt.Printf("%+v\n%#v\n", raspberry, raspberry)
// json encoding
fmt.Printf("---\njson encoding\n")
jsonData, err := json.Marshal(&raspberry)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonData))
// go-spew
fmt.Printf("---\ngo-spew\n")
spew.Dump(raspberry)
}
Output:
fmt.Printf with format verbs
{Name:raspberry color:pink Similar:0xc000070390}
main.Fruit{Name:"raspberry", color:"pink", Similar:(*main.Fruit)(0xc000070390)}
---
json encoding
{"Name":"raspberry","Similar":{"Name":"strawberry","Similar":null}}
---
go-spew
(main.Fruit) {
Name: (string) (len=9) "raspberry",
color: (string) (len=4) "pink",
Similar: (*main.Fruit)(0xc000070390)({
Name: (string) (len=10) "strawberry",
color: (string) (len=3) "red",
Similar: (*main.Fruit)(<nil>)
})
}
Note the differences:
fmt.Printf()
prints only field values, which in the case of a pointer, it is the memory address of the variable it points to.- Encoding to JSON requires all struct fields to be exported (the first letter capitalized). Otherwise, unexported fields such as
color
will not appear in the resulting JSON. - Package
go-spew
prints detailed information about the struct, but it is an external dependency that needs to be imported.
Depending on your use case, you should choose the method that suits you best.