How to print a map, struct or whatever in a readable way?
With PHP you can to this
echo '<pre>'; print_r($var); echo '</pre>';
or
header('content-type: text/plain'); print_r($var);
To print a variable's type, you can use the %T verb in the fmt. Printf() function format. It's the simplest and most recommended way of printing type of a variable. Alternatively, you can use the TypeOf() function from the reflection package reflect .
Use the Go fmt
package. For example,
package main import "fmt" func main() { variable := "var" fmt.Println(variable) fmt.Printf("%#v\n", variable) header := map[string]string{"content-type": "text/plain"} fmt.Println(header) fmt.Printf("%#v\n", header) }
Output:
var "var" map[content-type:text/plain] map[string]string{"content-type":"text/plain"}
Package fmt
import "fmt"
Overview
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.
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}} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With