print readable variables with golang

后端 未结 6 520

How to print a map, struct or whatever in a readable way?

With PHP you can to this

echo \'
\';
print_r($var);
echo \'
\';

6条回答
  •  误落风尘
    2021-02-04 03:06

    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
    }
    

提交回复
热议问题