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