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.

Indeed is quite easy to use the most common known package in the Go standard library: fmt. Which offers the following formatting option %+v.

%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 in the encoding/json package which always come with the standard library

The expected output at this point is the following

  "Endpoint": "/api/users",
  "ServicePortName": {
    "Name": "app.user",
    "Port": "9000"