如何以可读的方式打印地图,结构或其他内容?
使用PHP,你可以这样做
echo '<pre>';
print_r($var);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
要么
header('content-type: text/plain');
print_r($var);
Run Code Online (Sandbox Code Playgroud)
pet*_*rSO 14
使用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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
var
"var"
map[content-type:text/plain]
map[string]string{"content-type":"text/plain"}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)import "fmt"概观
包fmt实现了格式化的I/O,其功能类似于C的printf和scanf.格式'动词'来自C,但更简单.
我认为在许多情况下,使用“%v”足够简洁:
fmt.Printf("%v", myVar)
Run Code Online (Sandbox Code Playgroud)
在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}}
}
Run Code Online (Sandbox Code Playgroud)
您可以用来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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27056 次 |
| 最近记录: |