使用 golang 打印可读变量

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


使用 PHP 你可以做到这一点


echo '<pre>';

print_r($var);

echo '</pre>';

要么


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

print_r($var);


波斯汪
浏览 205回答 3
3回答

茅侃侃

使用 Gofmt包。例如,package mainimport "fmt"func main() {&nbsp; &nbsp; variable := "var"&nbsp; &nbsp; fmt.Println(variable)&nbsp; &nbsp; fmt.Printf("%#v\n", variable)&nbsp; &nbsp; header := map[string]string{"content-type": "text/plain"}&nbsp; &nbsp; fmt.Println(header)&nbsp; &nbsp; fmt.Printf("%#v\n", header)}输出:var"var"map[content-type:text/plain]map[string]string{"content-type":"text/plain"}包文件import "fmt"&nbsp;概述包 fmt 使用类似于 C 的 printf 和 scanf 的函数实现格式化的 I/O。“动词”格式源自 C,但更简单。

汪汪一只猫

我认为在很多情况下,使用 "%v" 已经足够简洁了:fmt.Printf("%v", myVar)从 fmt 包的文档页面:%v 默认格式的值。打印结构时,加号 ( %+v ) 添加字段名称%#v 值 的 Go 语法表示下面是一个例子:package mainimport "fmt"func main() {&nbsp; &nbsp; // Define a struct, slice and map&nbsp; &nbsp; type Employee struct {&nbsp; &nbsp; &nbsp; &nbsp; id&nbsp; &nbsp;int&nbsp; &nbsp; &nbsp; &nbsp; name string&nbsp; &nbsp; &nbsp; &nbsp; age&nbsp; int&nbsp; &nbsp; }&nbsp; &nbsp; var eSlice []Employee&nbsp; &nbsp; var eMap map[int]Employee&nbsp; &nbsp; e1 := Employee{1, "Alex", 20}&nbsp; &nbsp; e2 := Employee{2, "Jack", 30}&nbsp; &nbsp; fmt.Printf("%v\n", e1)&nbsp; &nbsp; // output: {1 Alex 20}&nbsp; &nbsp; fmt.Printf("%+v\n", e1)&nbsp; &nbsp; // output: {id:1 name:Alex age:20}&nbsp; &nbsp; fmt.Printf("%#v\n", e1)&nbsp; &nbsp; // output: main.Employee{id:1, name:"Alex", age:20}&nbsp; &nbsp; eSlice = append(eSlice, e1, e2)&nbsp; &nbsp; fmt.Printf("%v\n", eSlice)&nbsp; &nbsp; // output: [{1 Alex 20} {2 Jack 30}]&nbsp; &nbsp; fmt.Printf("%#v\n", eSlice)&nbsp; &nbsp; // output: []main.Employee{main.Employee{id:1, name:"Alex", age:20}, main.Employee{id:2, name:"Jack", age:30}}&nbsp; &nbsp; eMap = make(map[int]Employee)&nbsp; &nbsp; eMap[1] = e1&nbsp; &nbsp; eMap[2] = e2&nbsp; &nbsp; fmt.Printf("%v\n", eMap)&nbsp; &nbsp; // output: map[1:{1 Alex 20} 2:{2 Jack 30}]&nbsp; &nbsp; fmt.Printf("%#v\n", eMap)&nbsp; &nbsp; // output: map[int]main.Employee{1:main.Employee{id:1, name:"Alex", age:20}, 2:main.Employee{id:2, name:"Jack", age:30}}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go