How to print a map, struct or whatever in a readable way?
With PHP you can to this
echo \'\';
print_r($var);
echo \'
\';
I think in many cases, using "%v" is concise enough:
fmt.Printf("%v", myVar)
From the fmt package's documentation page:
%v the value in a default format. when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
Here is an example:
package main
import "fmt"
func main() {
// Define a struct, slice and map
type Employee struct {
id int
name string
age int
}
var eSlice []Employee
var eMap map[int]Employee
e1 := Employee{1, "Alex", 20}
e2 := Employee{2, "Jack", 30}
fmt.Printf("%v\n", e1)
// output: {1 Alex 20}
fmt.Printf("%+v\n", e1)
// output: {id:1 name:Alex age:20}
fmt.Printf("%#v\n", e1)
// output: main.Employee{id:1, name:"Alex", age:20}
eSlice = append(eSlice, e1, e2)
fmt.Printf("%v\n", eSlice)
// output: [{1 Alex 20} {2 Jack 30}]
fmt.Printf("%#v\n", eSlice)
// output: []main.Employee{main.Employee{id:1, name:"Alex", age:20}, main.Employee{id:2, name:"Jack", age:30}}
eMap = make(map[int]Employee)
eMap[1] = e1
eMap[2] = e2
fmt.Printf("%v\n", eMap)
// output: map[1:{1 Alex 20} 2:{2 Jack 30}]
fmt.Printf("%#v\n", eMap)
// output: map[int]main.Employee{1:main.Employee{id:1, name:"Alex", age:20}, 2:main.Employee{id:2, name:"Jack", age:30}}
}