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