天天看點

Golang 庫 - 格式化IO

1 格式化IO庫

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,才可以進行格式化列印。此時占位符才會發生作用。

2 占位符通用說明

%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,列印變量的類型。

3 不同資料類型的數值列印

其實統一用 %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[]           

複制

4 其他标記

+	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           

複制

5 格式化錯誤

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)           

複制

6 小結

在格式化 IO 時,%v,列印變量的具體數值。萬能列印,會根據變量的類型做調整。%T,列印變量的類型。

END