Go Printf用法


title : go printf用法
category : go
tag : go

go printf用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main

import (
"fmt"
"os"
"io"
)

type point struct {
x , y int
}

func main() {

p := point{1,2}
//%v 输出结构体值
fmt.Printf("%v\n",p) //{1 2}

//%+v 的格式化输出内容将包括结构体的字段名
fmt.Printf("%+v \n",p) //{x:1 y:2}

//%#v 形式则输出这个值的 Go 语法表示
fmt.Printf("%#v\n", p) //main.point{x:1, y:2}

//需要打印值的类型,使用 %T
fmt.Printf("%T\n", p) // main.point

//格式化布尔值
fmt.Printf("%t\n", true) //true

//%d 格式化整形
fmt.Printf("%d\n", 123) //123

//输出二进制表示形式
fmt.Printf("%b\n", 14) //1110


//输出给定整数的对应字符
fmt.Printf("%c\n", 33) //!

//%x 提供十六进制编码。
fmt.Printf("%x\n", 456) //1c8


//对于浮点型同样有很多的格式化选项。

// 使用 %f 进行最基本的十进制格式化。
fmt.Printf("%f\n", 78.9) //78.900000

//%e 和 %E 将浮点型格式化为(稍微有一点不同的)科学技科学记数法表示形式。
fmt.Printf("%e\n", 123400000.0) //1.234000e+08
fmt.Printf("%E\n", 123400000.0) //1.234000E+08

//使用 %s 进行基本的字符串输出。
fmt.Printf("%s\n", "\"string\"") //"string"

//像 Go 源代码中那样带有双引号的输出,使用 %q。
fmt.Printf("%q\n", "\"string\"") //"\"string\""

//和上面的整形数一样,%x 输出使用 base-16 编码的字符串,每个字节使用 2 个字符表示。
fmt.Printf("%x\n", "hex this")

//要输出一个指针的值,使用 %p。
fmt.Printf("%p\n", &p) //0xc8200721c0

//当输出数字的时候,你将经常想要控制输出结果的宽度和精度,可以使用在 % 后面使用数字来控制输出宽度。默认结果使用右对齐并且通过空格来填充空白部分。
fmt.Printf("|%6d|%6d|\n", 12, 345) //| 12| 345|

//你也可以指定浮点型的输出宽度,同时也可以通过 宽度.精度 的语法来指定输出的精度。
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) //| 1.20| 3.45|

//要最对齐,使用 - 标志。
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) //|1.20 |3.45 |

//你也许也想控制字符串输出时的宽度,特别是要确保他们在类表格输出时的对齐。这是基本的右对齐宽度表示。
fmt.Printf("|%6s|%6s|\n", "foo", "b") //| foo| b|

//要左对齐,和数字一样,使用 - 标志。
fmt.Printf("|%-6s|%-6s|\n", "foo", "b") //|foo |b |

//到目前为止,我们已经看过 Printf了,它通过 os.Stdout输出格式化的字符串。Sprintf 则格式化并返回一个字符串而不带任何输出。
s := fmt.Sprintf("a %s", "string")
fmt.Println(s) ///a string

//你可以使用 Fprintf 来格式化并输出到 io.Writers而不是 os.Stdout。
//fmt.Fprintf(os.Stderr, "an %s\n", "error")

}