Source file src/fmt/doc.go

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

View as plain text