github.com/hongwozai/go-src-1.4.3@v0.0.0-20191127132709-dc3fce3dbccb/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. -1234.456e+78 38 %E scientific notation, e.g. -1234.456E+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 42 %G %E for large exponents, %F otherwise 43 String and slice of bytes: 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 51 There is no 'u' flag. Integers are printed unsigned if they have unsigned type. 52 Similarly, there is no need to specify the size of the operand (int8, int64). 53 54 The default format for %v is: 55 bool: %t 56 int, int8 etc.: %d 57 uint, uint8 etc.: %d, %x if printed with %#v 58 float32, complex64, etc: %g 59 string: %s 60 chan: %p 61 pointer: %p 62 For compound objects, the elements are printed using these rules, recursively, 63 laid out like this: 64 struct: {field0 field1 ...} 65 array, slice: [elem0 elem1 ...] 66 maps: map[key1:value1 key2:value2] 67 pointer to above: &{}, &[], &map[] 68 69 Width is specified by an optional decimal number immediately following the verb. 70 If absent, the width is whatever is necessary to represent the value. 71 Precision is specified after the (optional) width by a period followed by a 72 decimal number. If no period is present, a default precision is used. 73 A period with no following number specifies a precision of zero. 74 Examples: 75 %f: default width, default precision 76 %9f width 9, default precision 77 %.2f default width, precision 2 78 %9.2f width 9, precision 2 79 %9.f width 9, precision 0 80 81 Width and precision are measured in units of Unicode code points, 82 that is, runes. (This differs from C's printf where the 83 units are always measured in bytes.) Either or both of the flags 84 may be replaced with the character '*', causing their values to be 85 obtained from the next operand, 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 it sets the total number of digits. For example, 99 given 123.45 the format %6.2f prints 123.45 while %.4g prints 123.5. 100 The default precision for %e and %f is 6; for %g it is the smallest 101 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 write e.g. U+0078 'x' if the character is printable for %U (%#U). 116 ' ' (space) leave a space for elided sign in numbers (% d); 117 put spaces between bytes printing strings or slices in hex (% x, % X) 118 0 pad with leading zeros rather than spaces; 119 for numbers, this moves the padding after the sign 120 121 Flags are ignored by verbs that do not expect them. 122 For example there is no alternate decimal format, so %#d and %d 123 behave identically. 124 125 For each Printf-like function, there is also a Print function 126 that takes no format and is equivalent to saying %v for every 127 operand. Another variant Println inserts blanks between 128 operands and appends a newline. 129 130 Regardless of the verb, if an operand is an interface value, 131 the internal concrete value is used, not the interface itself. 132 Thus: 133 var i interface{} = 23 134 fmt.Printf("%v\n", i) 135 will print 23. 136 137 Except when printed using the verbs %T and %p, special 138 formatting considerations apply for operands that implement 139 certain interfaces. In order of application: 140 141 1. If an operand implements the Formatter interface, it will 142 be invoked. Formatter provides fine control of formatting. 143 144 2. If the %v verb is used with the # flag (%#v) and the operand 145 implements the GoStringer interface, that will be invoked. 146 147 If the format (which is implicitly %v for Println etc.) is valid 148 for a string (%s %q %v %x %X), the following two rules apply: 149 150 3. If an operand implements the error interface, the Error method 151 will be invoked to convert the object to a string, which will then 152 be formatted as required by the verb (if any). 153 154 4. If an operand implements method String() string, that 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 For compound operands such as slices and structs, the format 159 applies to the elements of each operand, recursively, not to the 160 operand as a whole. Thus %q will quote each element of a slice 161 of strings, and %6.2f will control formatting for each element 162 of a floating-point array. 163 164 To avoid recursion in cases such as 165 type X string 166 func (x X) String() string { return Sprintf("<%s>", x) } 167 convert the value before recurring: 168 func (x X) String() string { return Sprintf("<%s>", string(x)) } 169 Infinite recursion can also be triggered by self-referential data 170 structures, such as a slice that contains itself as an element, if 171 that type has a String method. Such pathologies are rare, however, 172 and the package does not protect against them. 173 174 Explicit argument indexes: 175 176 In Printf, Sprintf, and Fprintf, the default behavior is for each 177 formatting verb to format successive arguments passed in the call. 178 However, the notation [n] immediately before the verb indicates that the 179 nth one-indexed argument is to be formatted instead. The same notation 180 before a '*' for a width or precision selects the argument index holding 181 the value. After processing a bracketed expression [n], arguments n+1, 182 n+2, etc. will be processed unless otherwise directed. 183 184 For example, 185 fmt.Sprintf("%[2]d %[1]d\n", 11, 22) 186 will yield "22 11", while 187 fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6), 188 equivalent to 189 fmt.Sprintf("%6.2f", 12.0), 190 will yield " 12.00". Because an explicit index affects subsequent verbs, 191 this notation can be used to print the same values multiple times 192 by resetting the index for the first argument to be repeated: 193 fmt.Sprintf("%d %d %#[1]x %#x", 16, 17) 194 will yield "16 17 0x10 0x11". 195 196 Format errors: 197 198 If an invalid argument is given for a verb, such as providing 199 a string to %d, the generated string will contain a 200 description of the problem, as in these examples: 201 202 Wrong type or unknown verb: %!verb(type=value) 203 Printf("%d", hi): %!d(string=hi) 204 Too many arguments: %!(EXTRA type=value) 205 Printf("hi", "guys"): hi%!(EXTRA string=guys) 206 Too few arguments: %!verb(MISSING) 207 Printf("hi%d"): hi %!d(MISSING) 208 Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC) 209 Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi 210 Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi 211 Invalid or invalid use of argument index: %!(BADINDEX) 212 Printf("%*[2]d", 7): %!d(BADINDEX) 213 Printf("%.[2]d", 7): %!d(BADINDEX) 214 215 All errors begin with the string "%!" followed sometimes 216 by a single character (the verb) and end with a parenthesized 217 description. 218 219 If an Error or String method triggers a panic when called by a 220 print routine, the fmt package reformats the error message 221 from the panic, decorating it with an indication that it came 222 through the fmt package. For example, if a String method 223 calls panic("bad"), the resulting formatted message will look 224 like 225 %!s(PANIC=bad) 226 227 The %!s just shows the print verb in use when the failure 228 occurred. 229 230 Scanning 231 232 An analogous set of functions scans formatted text to yield 233 values. Scan, Scanf and Scanln read from os.Stdin; Fscan, 234 Fscanf and Fscanln read from a specified io.Reader; Sscan, 235 Sscanf and Sscanln read from an argument string. Scanln, 236 Fscanln and Sscanln stop scanning at a newline and require that 237 the items be followed by one; Scanf, Fscanf and Sscanf require 238 newlines in the input to match newlines in the format; the other 239 routines treat newlines as spaces. 240 241 Scanf, Fscanf, and Sscanf parse the arguments according to a 242 format string, analogous to that of Printf. For example, %x 243 will scan an integer as a hexadecimal number, and %v will scan 244 the default representation format for the value. 245 246 The formats behave analogously to those of Printf with the 247 following exceptions: 248 249 %p is not implemented 250 %T is not implemented 251 %e %E %f %F %g %G are all equivalent and scan any floating point or complex value 252 %s and %v on strings scan a space-delimited token 253 Flags # and + are not implemented. 254 255 The familiar base-setting prefixes 0 (octal) and 0x 256 (hexadecimal) are accepted when scanning integers without a 257 format or with the %v verb. 258 259 Width is interpreted in the input text (%5s means at most 260 five runes of input will be read to scan a string) but there 261 is no syntax for scanning with a precision (no %5.2f, just 262 %5f). 263 264 When scanning with a format, all non-empty runs of space 265 characters (except newline) are equivalent to a single 266 space in both the format and the input. With that proviso, 267 text in the format string must match the input text; scanning 268 stops if it does not, with the return value of the function 269 indicating the number of arguments scanned. 270 271 In all the scanning functions, a carriage return followed 272 immediately by a newline is treated as a plain newline 273 (\r\n means the same as \n). 274 275 In all the scanning functions, if an operand implements method 276 Scan (that is, it implements the Scanner interface) that 277 method will be used to scan the text for that operand. Also, 278 if the number of arguments scanned is less than the number of 279 arguments provided, an error is returned. 280 281 All arguments to be scanned must be either pointers to basic 282 types or implementations of the Scanner interface. 283 284 Note: Fscan etc. can read one character (rune) past the input 285 they return, which means that a loop calling a scan routine 286 may skip some of the input. This is usually a problem only 287 when there is no space between input values. If the reader 288 provided to Fscan implements ReadRune, that method will be used 289 to read characters. If the reader also implements UnreadRune, 290 that method will be used to save the character and successive 291 calls will not lose data. To attach ReadRune and UnreadRune 292 methods to a reader without that capability, use 293 bufio.NewReader. 294 */ 295 package fmt