Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs’ are derived from C’s but are simpler.
fmt 包用于 格式化IO,类似于C语言的 printf 和 scanf。其占位符源自于C语言,但更加简单。
func Print(v ...interface{})
func Printf(format string, v ...interface{})
func Println(v ...interface{})
有且仅在 [f] 结尾的打印接口中,f 表示 format,才可以进行格式化打印。此时占位符才会发生作用。
%v the value in a default format
when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
%T a Go-syntax representation of the type of the value
%% a literal percent sign; consumes no value
%v,打印变量的具体数值。万能打印,会根据变量的类型做调整。 %T,打印变量的类型。
其实统一用 %v 就很省事了。
bool: %t
int, int8 etc.: %d
uint, uint8 etc.: %d, %x if printed with %#v
float32, complex64, etc: %g
string: %s
chan: %p
pointer: %p
复杂数据类型的格式化是这样:
struct: {field0 field1 ...}
array, slice: [elem0 elem1 ...]
maps: map[key1:value1 key2:value2]
pointer to above: &{}, &[], &map[]
+ always print a sign for numeric values;
guarantee ASCII-only output for %q (%+q)
- pad with spaces on the right rather than the left (left-justify the field)
# alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
for %q, print a raw (backquoted) string if strconv.CanBackquote
returns true;
always print a decimal point for %e, %E, %f, %F, %g and %G;
do not remove trailing zeros for %g and %G;
write e.g. U+0078 'x' if the character is printable for %U (%#U).
' ' (space) leave a space for elided sign in numbers (% d);
put spaces between bytes printing strings or slices in hex (% x, % X)
0 pad with leading zeros rather than spaces;
for numbers, this moves the padding after the sign
看下来应该应该是空格填充比较有用,做个小测试。
u1 := []byte {0x31, 0x32}
log.Printf("0x:%x\n", u1)
log.Printf("0x:% x\n", u1)
输出
0x:3132
0x:31 32
Wrong type or unknown verb: %!verb(type=value)
Printf("%d", "hi"): %!d(string=hi)
Too many arguments: %!(EXTRA type=value)
Printf("hi", "guys"): hi%!(EXTRA string=guys)
Too few arguments: %!verb(MISSING)
Printf("hi%d"): hi%!d(MISSING)
Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi
Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
Invalid or invalid use of argument index: %!(BADINDEX)
Printf("%*[2]d", 7): %!d(BADINDEX)
Printf("%.[2]d", 7): %!d(BADINDEX)
所有的错误都始于“%!”,有时紧跟着单个字符(占位符),并以小括号括住的描述结尾。
也做个最常见的示例,错误格式的占位符。
log.Printf("%t", 1)
打印如下:
%!t(int=1)
在格式化 IO 时,%v,打印变量的具体数值。万能打印,会根据变量的类型做调整。%T,打印变量的类型。