字符串格式化输出
package main import "fmt" import "os" type point struct { x, y int } func main() { // 创建一个point struct p := point{1, 2} // 输出struct的值 {1 2} fmt.Printf("%v\n", p) // 输出struct的值和字段 {x:1 y:2} fmt.Printf("%+v\n", p) // 输出struct的类型和字段和值 main.point{x:1, y:2} fmt.Printf("%#v\n", p) // 输出类型 main.point fmt.Printf("%T\n", p) // 输出整齐的排列 true fmt.Printf("%t\n", true) // 输出数字 123 fmt.Printf("%d\n", 123) // 输出二进制 fmt.Printf("%b\n", 14) // 将int输出为char型 fmt.Printf("%c\n", 33) // 输出16进制 1c8 fmt.Printf("%x\n", 456) // 格式化输出float型 78.900000 fmt.Printf("%f\n", 78.9) // 1.234000e+08 // 1.234000E+08 fmt.Printf("%e\n", 123400000.0) fmt.Printf("%E\n", 123400000.0) // 基础的字符串输出 "string" fmt.Printf("%s\n", "\"string\"") // 带引用的基础的字符串输出 "\"string\"" fmt.Printf("%q\n", "\"string\"") // 输出byte 6865782074686973 fmt.Printf("%x\n", "hex this") // 输出地址 0x42135100 fmt.Printf("%p\n", &p) // 右对齐输出 | 12| 345| fmt.Printf("|%6d|%6d|\n", 12, 345) // 右对齐输出 | 1.20| 3.45| fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // 使用- flag,左对齐输出 |1.20 |3.45 | fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // 右对齐输出 | foo| b| fmt.Printf("|%6s|%6s|\n", "foo", "b") // 使用- flag,左对齐输出 |foo |b | fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // 只返回数据不输出 s := fmt.Sprintf("a %s", "string") fmt.Println(s) // You can format+print to io.Writers other than os.Stdout using Fprintf. fmt.Fprintf(os.Stderr, "an %s\n", "error") }有疑问加站长微信联系(非本文作者)
