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