用golang打印可读变量

时间:2014-09-25 17:59:20

标签: go

如何以可读的方式打印地图,结构或其他内容?

使用PHP,您可以使用

echo '<pre>';
print_r($var);
echo '</pre>';

header('content-type: text/plain');
print_r($var);

6 个答案:

答案 0 :(得分:11)

使用Go fmt包。例如,

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)
}

输出:

var
"var"
map[content-type:text/plain]
map[string]string{"content-type":"text/plain"}
  

Package fmt

import "fmt" 
     

概述

     

软件包fmt使用类似于C的函数实现格式化的I / O.   printf和scanf。格式'动词'来自C,但是   简单。

答案 1 :(得分:4)

我认为在很多情况下,使用&#34;%v&#34;很简洁:

fmt.Printf("%v", myVar)

来自fmt软件包的文档页面:

  

%v 默认格式的值。         打印结构时,加号标志(%+ v )会添加字段名称

     

%#v

的Go语法表示

以下是一个例子:

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}}
}

答案 2 :(得分:3)

您可以使用fmt.Println()进行打印。您需要导入“fmt”包(请参阅下面的示例)。许多数据类型都可以打印出来。如果您想获得自定义类型的人类可读打印件,则需要为该类型定义String() string方法。

要尝试以下示例,请点击此处: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
}

答案 3 :(得分:1)

fmt.Printf("%v", whatever) 

在Go中就像PHP中的print_r(),var_dump(),var_export()。 (%v是重要的部分。)

祝你好运

答案 4 :(得分:0)

对于调试我使用:

func printVars(w io.Writer, writePre bool, vars ...interface{}) {
    if writePre {
        io.WriteString(w, "<pre>\n")
    }
    for i, v := range vars {
        fmt.Fprintf(w, "» item %d type %T:\n", i, v)
        j, err := json.MarshalIndent(v, "", "    ")
        switch {
        case err != nil:
            fmt.Fprintf(w, "error: %v", err)
        case len(j) < 3: // {}, empty struct maybe or empty string, usually mean unexported struct fields
            w.Write([]byte(html.EscapeString(fmt.Sprintf("%+v", v))))
        default:
            w.Write(j)
        }
        w.Write([]byte("\n\n"))
    }
    if writePre {
        io.WriteString(w, "</pre>\n")
    }
}

playground

答案 5 :(得分:0)

https://github.com/davecgh/go-spew

  

Go-spew为Go数据结构实现了一个非常漂亮的打印机,以帮助调试。