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