How to print a map, struct or whatever in a readable way?
With PHP you can to this
echo \'\';
print_r($var);
echo \'
\';
You can use fmt.Println()
to print. You will need to import the "fmt" package (see the example below). Many data types can be printed out of the box. If you want to get a human-readable print for custom types, you'll need to define a String() string
method for that type.
To try the following example, click here: http://play.golang.org/p/M6_KnRJ3Da
package main
import "fmt"
// No `String()` method
type UnstringablePerson struct {
Age int
Name string
}
// Has a `String()` method
type StringablePerson struct {
Age int
Name string
}
// Let's define a String() method for StringablePerson, so any instances
// of StringablePerson can be printed how we like
func (p *StringablePerson) String() string {
return fmt.Sprintf("%s, age %d", p.Name, p.Age)
}
func main() {
// Bobby's type is UnstringablePerson; there is no String() method
// defined for this type, so his printout will not be very friendly
bobby := &UnstringablePerson{
Age: 10,
Name: "Bobby",
}
// Ralph's type is StringablePerson; there *is* a String() method
// defined for this type, so his printout *will* be very friendly
ralph := &StringablePerson{
Age: 12,
Name: "Ralph",
}
fmt.Println(bobby) // prints: &{10 Bobby}
fmt.Println(ralph) // prints: Ralph, age 12
}