How to print struct variables in golang
You might sometimes wonder how to print struct variables in Go in order to inspect the value for debugging purposes. Here it comes a simple example where we have a struct with a string and a pointer to another struct. Which consenquently has two string values.
package main
import (
"fmt"
)
type ServicePortName struct {
Name string
Port string
}
type ServiceEndpoint struct {
Endpoint string
ServicePortName *ServicePortName
}
func main() {
svc := &ServiceEndpoint{"/api/users", &ServicePortName{"app.user", "9000"}}
fmt.Printf("%+v", svc)
}
Indeed is quite easy to use the most common known package in the Go standard library: fmt
. Which offers the following formatting option %+v
. https://golang.org/pkg/fmt/#hdr-Printing.
%v the value in a default format
when printing structs, the plus flag (%+v) adds field names
This is the expected output from the above code snippet
{Endpoint:/api/users ServicePortName: 0x40a0f0}
At this point we also want to be able to inspect the struct value referenced by the struct pointer *ServicePortName
An easy way to recursively printing all the values from a given variable we can use an handy method https://golang.org/pkg/encoding/json/#MarshalIndent in the encoding/json
package which always come with the standard library
package main
import (
"fmt"
"encoding/json"
)
type ServicePortName struct {
Name string
Port string
}
type ServiceEndpoint struct {
Endpoint string
ServicePortName *ServicePortName
}
func main() {
svc := &ServiceEndpoint{"/api/users", &ServicePortName{"app.user", "9000"}}
s, _ := json.MarshalIndent(svc, "", "\t")
fmt.Println(string(s))
}
The expected output at this point is the following
{
"Endpoint": "/api/users",
"ServicePortName": {
"Name": "app.user",
"Port": "9000"
}
}
Ready for your next Golang Job? Join other fellow Gophers, submit your profile and get hired