Go语言fmt包通过格式动词实现灵活输出:1. %v、%+v、%#v分别输出值、结构体字段及Go语法格式;2. %t、%d、%b、%o、%x等处理布尔和整数;3. %f、%e、%g控制浮点数;4. %s、%q格式化字符串;5. 宽度、精度和对齐通过%N、%.N等控制,提升输出可读性。

Go语言中的
fmt
格式动词以
%
type Person struct {
Name string
Age int
}
p := Person{"Alice", 30}
fmt.Printf("%v\n", p) // 输出:{Alice 30}
fmt.Printf("%+v\n", p) // 输出:{Name:Alice Age:30}
fmt.Printf("%#v\n", p) // 输出:main.Person{Name:"Alice", Age:30}
fmt.Printf("%T\n", p) // 输出:main.Person
针对布尔和数值类型,有专门的格式动词:
n := 255
fmt.Printf("%d\n", n) // 输出:255
fmt.Printf("%b\n", n) // 输出:11111111
fmt.Printf("%o\n", n) // 输出:377
fmt.Printf("%x\n", n) // 输出:ff
fmt.Printf("%X\n", n) // 输出:FF
fmt.Printf("%U\n", '中') // 输出:U+4E2D
fmt.Printf("%c\n", '中') // 输出:中
处理浮点数和字符串时,格式动词能更精细地控制输出精度和形式:
立即学习“go语言免费学习笔记(深入)”;
f := 123.456789
fmt.Printf("%.2f\n", f) // 输出:123.46(保留两位小数)
fmt.Printf("%.2e\n", f) // 输出:1.23e+02
fmt.Printf("%g\n", f) // 输出:123.456789
str := "hello"
fmt.Printf("%s\n", str) // 输出:hello
fmt.Printf("%q\n", str) // 输出:"hello"
fmt.Printf("%x\n", str) // 输出:68656c6c6f
可以在动词前添加参数控制输出宽度、精度和对齐方式:
fmt.Printf("|%10s|\n", "hi") // 输出:| hi|
fmt.Printf("|%-10s|\n", "hi") // 输出:|hi |
fmt.Printf("|%05d|\n", 42) // 输出:|00042|
fmt.Printf("%.3s\n", "hello") // 输出:hel
fmt
以上就是Golang fmt格式化输出 动词使用详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号