print readable variables with golang

huangapple go评论70阅读模式
英文:

print readable variables with golang

问题

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

使用PHP,你可以这样做:

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

或者

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

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

With PHP you can to this

echo &#39;&lt;pre&gt;&#39;;
print_r($var);
echo &#39;&lt;/pre&gt;&#39;;

or

header(&#39;content-type: text/plain&#39;);
print_r($var);

答案1

得分: 19

使用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"}

> fmt包
>
> import "fmt"
>
> 概述
>
> 包fmt实现了类似于C的printf和scanf的格式化I/O。格式化的“动词”源自C,但更简单。

英文:

Use the Go fmt package. For example,

package main

import &quot;fmt&quot;

func main() {
	variable := &quot;var&quot;
	fmt.Println(variable)
	fmt.Printf(&quot;%#v\n&quot;, variable)
	header := map[string]string{&quot;content-type&quot;: &quot;text/plain&quot;}
	fmt.Println(header)
	fmt.Printf(&quot;%#v\n&quot;, header)
}

Output:

var
&quot;var&quot;
map[content-type:text/plain]
map[string]string{&quot;content-type&quot;:&quot;text/plain&quot;}

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

答案2

得分: 15

我认为在许多情况下,使用"%v"已经足够简洁了:

fmt.Printf("%v", myVar)

根据fmt包的文档页面:

  • %v:以默认格式打印值。当打印结构体时,加号标志(%+v)会添加字段名。
  • %#v:以Go语法表示的值的表示形式。

以下是一个示例:

package main

import "fmt"

func main() {
    // 定义一个结构体、切片和映射
    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)
    // 输出:{1 Alex 20}
    fmt.Printf("%+v\n", e1)
    // 输出:{id:1 name:Alex age:20}
    fmt.Printf("%#v\n", e1)
    // 输出:main.Employee{id:1, name:"Alex", age:20}

    eSlice = append(eSlice, e1, e2)
    fmt.Printf("%v\n", eSlice)
    // 输出:[{1 Alex 20} {2 Jack 30}]
    fmt.Printf("%#v\n", eSlice)
    // 输出:[]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)
    // 输出:map[1:{1 Alex 20} 2:{2 Jack 30}]
    fmt.Printf("%#v\n", eMap)
    // 输出:map[int]main.Employee{1:main.Employee{id:1, name:"Alex", age:20}, 2:main.Employee{id:2, name:"Jack", age:30}}
}
英文:

I think in many cases, using "%v" is concise enough:

fmt.Printf(&quot;%v&quot;, 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 &quot;fmt&quot;

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, &quot;Alex&quot;, 20}
	e2 := Employee{2, &quot;Jack&quot;, 30}
	fmt.Printf(&quot;%v\n&quot;, e1)
	// output: {1 Alex 20}
	fmt.Printf(&quot;%+v\n&quot;, e1)
	// output: {id:1 name:Alex age:20}
	fmt.Printf(&quot;%#v\n&quot;, e1)
	// output: main.Employee{id:1, name:&quot;Alex&quot;, age:20}

	eSlice = append(eSlice, e1, e2)
	fmt.Printf(&quot;%v\n&quot;, eSlice)
	// output: [{1 Alex 20} {2 Jack 30}]
	fmt.Printf(&quot;%#v\n&quot;, eSlice)
	// output: []main.Employee{main.Employee{id:1, name:&quot;Alex&quot;, age:20}, main.Employee{id:2, name:&quot;Jack&quot;, age:30}}

	eMap = make(map[int]Employee)
	eMap[1] = e1
	eMap[2] = e2
	fmt.Printf(&quot;%v\n&quot;, eMap)
	// output: map[1:{1 Alex 20} 2:{2 Jack 30}]
	fmt.Printf(&quot;%#v\n&quot;, eMap)
	// output: map[int]main.Employee{1:main.Employee{id:1, name:&quot;Alex&quot;, age:20}, 2:main.Employee{id:2, name:&quot;Jack&quot;, age:30}}
}

答案3

得分: 5

你可以使用fmt.Println()来打印输出。你需要导入"fmt"包(参见下面的示例)。许多数据类型可以直接打印输出。如果你想要为自定义类型获得可读性强的打印输出,你需要为该类型定义一个String() string方法。

要尝试下面的示例,请点击这里:http://play.golang.org/p/M6_KnRJ3Da

package main

import "fmt"

// 没有`String()`方法
type UnstringablePerson struct {
    Age  int
    Name string
}

// 有`String()`方法
type StringablePerson struct {
    Age  int
    Name string
}

// 让我们为StringablePerson定义一个String()方法,这样任何StringablePerson的实例都可以按我们喜欢的方式打印出来
func (p *StringablePerson) String() string {
    return fmt.Sprintf("%s, age %d", p.Name, p.Age)
}

func main() {
    // Bobby的类型是UnstringablePerson;对于这种类型,没有定义String()方法,所以他的打印输出不太友好
    bobby := &UnstringablePerson{
        Age:  10,
        Name: "Bobby",
    }

    // Ralph的类型是StringablePerson;对于这种类型,*有*定义String()方法,所以他的打印输出*会*很友好
    ralph := &StringablePerson{
        Age:  12,
        Name: "Ralph",
    }
    fmt.Println(bobby) // 输出:&{10 Bobby}
    fmt.Println(ralph) // 输出:Ralph, age 12
}
英文:

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 &quot;fmt&quot;

// No `String()` method
type UnstringablePerson struct {
	Age int
	Name string
}

// Has a `String()` method
type StringablePerson struct {
	Age int
	Name string
}

// Let&#39;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(&quot;%s, age %d&quot;, p.Name, p.Age)
}

func main() {
    // Bobby&#39;s type is UnstringablePerson; there is no String() method
    // defined for this type, so his printout will not be very friendly
	bobby := &amp;UnstringablePerson{
		Age: 10,
		Name: &quot;Bobby&quot;,
	}

    // Ralph&#39;s type is StringablePerson; there *is* a String() method
    // defined for this type, so his printout *will* be very friendly
	ralph := &amp;StringablePerson{
		Age: 12,
		Name: &quot;Ralph&quot;,
	}
	fmt.Println(bobby) // prints: &amp;{10 Bobby}
	fmt.Println(ralph) // prints: Ralph, age 12
}

答案4

得分: 3

go-spew是一个用于Go数据结构的深度漂亮打印机,以帮助调试。你可以在https://github.com/davecgh/go-spew找到它。

英文:

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

> Go-spew implements a deep pretty printer for Go data structures to aid in debugging.

答案5

得分: 2

你好!以下是翻译好的内容:

fmt.Printf("%v", whatever)

在Go语言中,这类似于PHP中的print_r()、var_dump()和var_export()函数。(%v是其中重要的部分。)

祝你好运!

英文:
fmt.Printf(&quot;%v&quot;, whatever) 

In Go is like print_r(), var_dump(), var_export() in PHP. (The %v is the important part.)

Good Luck

答案6

得分: 1

用于调试的代码如下:

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

[kbd]playground/kbd

英文:

For debugging I use this:

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

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年9月26日 01:59:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26045106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定