github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/fmt/doc.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  /*
     6  	Package fmt implements formatted I/O with functions analogous
     7  	to C's printf and scanf.  The format 'verbs' are derived from C's but
     8  	are simpler.
     9  
    10  
    11  	Printing
    12  
    13  	The verbs:
    14  
    15  	General:
    16  		%v	the value in a default format
    17  			when printing structs, the plus flag (%+v) adds field names
    18  		%#v	a Go-syntax representation of the value
    19  		%T	a Go-syntax representation of the type of the value
    20  		%%	a literal percent sign; consumes no value
    21  
    22  	Boolean:
    23  		%t	the word true or false
    24  	Integer:
    25  		%b	base 2
    26  		%c	the character represented by the corresponding Unicode code point
    27  		%d	base 10
    28  		%o	base 8
    29  		%q	a single-quoted character literal safely escaped with Go syntax.
    30  		%x	base 16, with lower-case letters for a-f
    31  		%X	base 16, with upper-case letters for A-F
    32  		%U	Unicode format: U+1234; same as "U+%04X"
    33  	Floating-point and complex constituents:
    34  		%b	decimalless scientific notation with exponent a power of two,
    35  			in the manner of strconv.FormatFloat with the 'b' format,
    36  			e.g. -123456p-78
    37  		%e	scientific notation, e.g. -1.234456e+78
    38  		%E	scientific notation, e.g. -1.234456E+78
    39  		%f	decimal point but no exponent, e.g. 123.456
    40  		%F	synonym for %f
    41  		%g	%e for large exponents, %f otherwise. Precision is discussed below.
    42  		%G	%E for large exponents, %F otherwise
    43  	String and slice of bytes (treated equivalently with these verbs):
    44  		%s	the uninterpreted bytes of the string or slice
    45  		%q	a double-quoted string safely escaped with Go syntax
    46  		%x	base 16, lower-case, two characters per byte
    47  		%X	base 16, upper-case, two characters per byte
    48  	Pointer:
    49  		%p	base 16 notation, with leading 0x
    50  
    51  	The default format for %v is:
    52  		bool:                    %t
    53  		int, int8 etc.:          %d
    54  		uint, uint8 etc.:        %d, %#x if printed with %#v
    55  		float32, complex64, etc: %g
    56  		string:                  %s
    57  		chan:                    %p
    58  		pointer:                 %p
    59  	For compound objects, the elements are printed using these rules, recursively,
    60  	laid out like this:
    61  		struct:             {field0 field1 ...}
    62  		array, slice:       [elem0 elem1 ...]
    63  		maps:               map[key1:value1 key2:value2]
    64  		pointer to above:   &{}, &[], &map[]
    65  
    66  	Width is specified by an optional decimal number immediately preceding the verb.
    67  	If absent, the width is whatever is necessary to represent the value.
    68  	Precision is specified after the (optional) width by a period followed by a
    69  	decimal number. If no period is present, a default precision is used.
    70  	A period with no following number specifies a precision of zero.
    71  	Examples:
    72  		%f     default width, default precision
    73  		%9f    width 9, default precision
    74  		%.2f   default width, precision 2
    75  		%9.2f  width 9, precision 2
    76  		%9.f   width 9, precision 0
    77  
    78  	Width and precision are measured in units of Unicode code points,
    79  	that is, runes. (This differs from C's printf where the
    80  	units are always measured in bytes.) Either or both of the flags
    81  	may be replaced with the character '*', causing their values to be
    82  	obtained from the next operand, which must be of type int.
    83  
    84  	For most values, width is the minimum number of runes to output,
    85  	padding the formatted form with spaces if necessary.
    86  
    87  	For strings, byte slices and byte arrays, however, precision
    88  	limits the length of the input to be formatted (not the size of
    89  	the output), truncating if necessary. Normally it is measured in
    90  	runes, but for these types when formatted with the %x or %X format
    91  	it is measured in bytes.
    92  
    93  	For floating-point values, width sets the minimum width of the field and
    94  	precision sets the number of places after the decimal, if appropriate,
    95  	except that for %g/%G precision sets the total number of significant
    96  	digits. For example, given 12.345 the format %6.3f prints 12.345 while
    97  	%.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it
    98  	is the smallest number of digits necessary to identify the value uniquely.
    99  
   100  	For complex numbers, the width and precision apply to the two
   101  	components independently and the result is parenthesized, so %f applied
   102  	to 1.2+3.4i produces (1.200000+3.400000i).
   103  
   104  	Other flags:
   105  		+	always print a sign for numeric values;
   106  			guarantee ASCII-only output for %q (%+q)
   107  		-	pad with spaces on the right rather than the left (left-justify the field)
   108  		#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
   109  			0X for hex (%#X); suppress 0x for %p (%#p);
   110  			for %q, print a raw (backquoted) string if strconv.CanBackquote
   111  			returns true;
   112  			always print a decimal point for %e, %E, %f, %F, %g and %G;
   113  			do not remove trailing zeros for %g and %G;
   114  			write e.g. U+0078 'x' if the character is printable for %U (%#U).
   115  		' '	(space) leave a space for elided sign in numbers (% d);
   116  			put spaces between bytes printing strings or slices in hex (% x, % X)
   117  		0	pad with leading zeros rather than spaces;
   118  			for numbers, this moves the padding after the sign
   119  
   120  	Flags are ignored by verbs that do not expect them.
   121  	For example there is no alternate decimal format, so %#d and %d
   122  	behave identically.
   123  
   124  	For each Printf-like function, there is also a Print function
   125  	that takes no format and is equivalent to saying %v for every
   126  	operand.  Another variant Println inserts blanks between
   127  	operands and appends a newline.
   128  
   129  	Regardless of the verb, if an operand is an interface value,
   130  	the internal concrete value is used, not the interface itself.
   131  	Thus:
   132  		var i interface{} = 23
   133  		fmt.Printf("%v\n", i)
   134  	will print 23.
   135  
   136  	Except when printed using the verbs %T and %p, special
   137  	formatting considerations apply for operands that implement
   138  	certain interfaces. In order of application:
   139  
   140  	1. If the operand is a reflect.Value, the operand is replaced by the
   141  	concrete value that it holds, and printing continues with the next rule.
   142  
   143  	2. If an operand implements the Formatter interface, it will
   144  	be invoked. Formatter provides fine control of formatting.
   145  
   146  	3. If the %v verb is used with the # flag (%#v) and the operand
   147  	implements the GoStringer interface, that will be invoked.
   148  
   149  	If the format (which is implicitly %v for Println etc.) is valid
   150  	for a string (%s %q %v %x %X), the following two rules apply:
   151  
   152  	4. If an operand implements the error interface, the Error method
   153  	will be invoked to convert the object to a string, which will then
   154  	be formatted as required by the verb (if any).
   155  
   156  	5. If an operand implements method String() string, that method
   157  	will be invoked to convert the object to a string, which will then
   158  	be formatted as required by the verb (if any).
   159  
   160  	For compound operands such as slices and structs, the format
   161  	applies to the elements of each operand, recursively, not to the
   162  	operand as a whole. Thus %q will quote each element of a slice
   163  	of strings, and %6.2f will control formatting for each element
   164  	of a floating-point array.
   165  
   166  	However, when printing a byte slice with a string-like verb
   167  	(%s %q %x %X), it is treated identically to a string, as a single item.
   168  
   169  	To avoid recursion in cases such as
   170  		type X string
   171  		func (x X) String() string { return Sprintf("<%s>", x) }
   172  	convert the value before recurring:
   173  		func (x X) String() string { return Sprintf("<%s>", string(x)) }
   174  	Infinite recursion can also be triggered by self-referential data
   175  	structures, such as a slice that contains itself as an element, if
   176  	that type has a String method. Such pathologies are rare, however,
   177  	and the package does not protect against them.
   178  
   179  	When printing a struct, fmt cannot and therefore does not invoke
   180  	formatting methods such as Error or String on unexported fields.
   181  
   182  	Explicit argument indexes:
   183  
   184  	In Printf, Sprintf, and Fprintf, the default behavior is for each
   185  	formatting verb to format successive arguments passed in the call.
   186  	However, the notation [n] immediately before the verb indicates that the
   187  	nth one-indexed argument is to be formatted instead. The same notation
   188  	before a '*' for a width or precision selects the argument index holding
   189  	the value. After processing a bracketed expression [n], subsequent verbs
   190  	will use arguments n+1, n+2, etc. unless otherwise directed.
   191  
   192  	For example,
   193  		fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
   194  	will yield "22 11", while
   195  		fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6),
   196  	equivalent to
   197  		fmt.Sprintf("%6.2f", 12.0),
   198  	will yield " 12.00". Because an explicit index affects subsequent verbs,
   199  	this notation can be used to print the same values multiple times
   200  	by resetting the index for the first argument to be repeated:
   201  		fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
   202  	will yield "16 17 0x10 0x11".
   203  
   204  	Format errors:
   205  
   206  	If an invalid argument is given for a verb, such as providing
   207  	a string to %d, the generated string will contain a
   208  	description of the problem, as in these examples:
   209  
   210  		Wrong type or unknown verb: %!verb(type=value)
   211  			Printf("%d", hi):          %!d(string=hi)
   212  		Too many arguments: %!(EXTRA type=value)
   213  			Printf("hi", "guys"):      hi%!(EXTRA string=guys)
   214  		Too few arguments: %!verb(MISSING)
   215  			Printf("hi%d"):            hi%!d(MISSING)
   216  		Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
   217  			Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
   218  			Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
   219  		Invalid or invalid use of argument index: %!(BADINDEX)
   220  			Printf("%*[2]d", 7):       %!d(BADINDEX)
   221  			Printf("%.[2]d", 7):       %!d(BADINDEX)
   222  
   223  	All errors begin with the string "%!" followed sometimes
   224  	by a single character (the verb) and end with a parenthesized
   225  	description.
   226  
   227  	If an Error or String method triggers a panic when called by a
   228  	print routine, the fmt package reformats the error message
   229  	from the panic, decorating it with an indication that it came
   230  	through the fmt package.  For example, if a String method
   231  	calls panic("bad"), the resulting formatted message will look
   232  	like
   233  		%!s(PANIC=bad)
   234  
   235  	The %!s just shows the print verb in use when the failure
   236  	occurred. If the panic is caused by a nil receiver to an Error
   237  	or String method, however, the output is the undecorated
   238  	string, "<nil>".
   239  
   240  	Scanning
   241  
   242  	An analogous set of functions scans formatted text to yield
   243  	values.  Scan, Scanf and Scanln read from os.Stdin; Fscan,
   244  	Fscanf and Fscanln read from a specified io.Reader; Sscan,
   245  	Sscanf and Sscanln read from an argument string.
   246  
   247  	Scan, Fscan, Sscan treat newlines in the input as spaces.
   248  
   249  	Scanln, Fscanln and Sscanln stop scanning at a newline and
   250  	require that the items be followed by a newline or EOF.
   251  
   252  	Scanf, Fscanf, and Sscanf parse the arguments according to a
   253  	format string, analogous to that of Printf. In the text that
   254  	follows, 'space' means any Unicode whitespace character
   255  	except newline.
   256  
   257  	In the format string, a verb introduced by the % character
   258  	consumes and parses input; these verbs are described in more
   259  	detail below. A character other than %, space, or newline in
   260  	the format consumes exactly that input character, which must
   261  	be present. A newline with zero or more spaces before it in
   262  	the format string consumes zero or more spaces in the input
   263  	followed by a single newline or the end of the input. A space
   264  	following a newline in the format string consumes zero or more
   265  	spaces in the input. Otherwise, any run of one or more spaces
   266  	in the format string consumes as many spaces as possible in
   267  	the input. Unless the run of spaces in the format string
   268  	appears adjacent to a newline, the run must consume at least
   269  	one space from the input or find the end of the input.
   270  
   271  	The handling of spaces and newlines differs from that of C's
   272  	scanf family: in C, newlines are treated as any other space,
   273  	and it is never an error when a run of spaces in the format
   274  	string finds no spaces to consume in the input.
   275  
   276  	The verbs behave analogously to those of Printf.
   277  	For example, %x will scan an integer as a hexadecimal number,
   278  	and %v will scan the default representation format for the value.
   279  	The Printf verbs %p and %T and the flags # and + are not implemented,
   280  	and the verbs %e %E %f %F %g and %G are all equivalent and scan any
   281  	floating-point or complex value.
   282  
   283  	Input processed by verbs is implicitly space-delimited: the
   284  	implementation of every verb except %c starts by discarding
   285  	leading spaces from the remaining input, and the %s verb
   286  	(and %v reading into a string) stops consuming input at the first
   287  	space or newline character.
   288  
   289  	The familiar base-setting prefixes 0 (octal) and 0x
   290  	(hexadecimal) are accepted when scanning integers without
   291  	a format or with the %v verb.
   292  
   293  	Width is interpreted in the input text but there is no
   294  	syntax for scanning with a precision (no %5.2f, just %5f).
   295  	If width is provided, it applies after leading spaces are
   296  	trimmed and specifies the maximum number of runes to read
   297  	to satisfy the verb. For example,
   298  	   Sscanf(" 1234567 ", "%5s%d", &s, &i)
   299  	will set s to "12345" and i to 67 while
   300  	   Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
   301  	will set s to "12" and i to 34.
   302  
   303  	In all the scanning functions, a carriage return followed
   304  	immediately by a newline is treated as a plain newline
   305  	(\r\n means the same as \n).
   306  
   307  	In all the scanning functions, if an operand implements method
   308  	Scan (that is, it implements the Scanner interface) that
   309  	method will be used to scan the text for that operand.  Also,
   310  	if the number of arguments scanned is less than the number of
   311  	arguments provided, an error is returned.
   312  
   313  	All arguments to be scanned must be either pointers to basic
   314  	types or implementations of the Scanner interface.
   315  
   316  	Like Scanf and Fscanf, Sscanf need not consume its entire input.
   317  	There is no way to recover how much of the input string Sscanf used.
   318  
   319  	Note: Fscan etc. can read one character (rune) past the input
   320  	they return, which means that a loop calling a scan routine
   321  	may skip some of the input.  This is usually a problem only
   322  	when there is no space between input values.  If the reader
   323  	provided to Fscan implements ReadRune, that method will be used
   324  	to read characters.  If the reader also implements UnreadRune,
   325  	that method will be used to save the character and successive
   326  	calls will not lose data.  To attach ReadRune and UnreadRune
   327  	methods to a reader without that capability, use
   328  	bufio.NewReader.
   329  */
   330  package fmt