Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print readable variables with golang

Tags:

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); 
like image 838
clarkk Avatar asked Sep 25 '14 17:09

clarkk


People also ask

How do you print a variable in Go lang?

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 .


2 Answers

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.

like image 74
peterSO Avatar answered Oct 01 '22 15:10

peterSO


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}} } 
like image 21
Kurt Zhong Avatar answered Oct 01 '22 13:10

Kurt Zhong