Rebase.
[official-gcc.git] / libgo / go / fmt / doc.go
blob02642d6ae775d6700e3448174cbf1d316893ec13
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.
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.
11 Printing
13 The verbs:
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
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 whichever of %e or %f produces more compact output
42 %G whichever of %E or %f produces more compact output
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
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).
54 Width is specified by an optional decimal number immediately following the verb.
55 If absent, the width is whatever is necessary to represent the value.
56 Precision is specified after the (optional) width by a period followed by a
57 decimal number. If no period is present, a default precision is used.
58 A period with no following number specifies a precision of zero.
59 Examples:
60 %f: default width, default precision
61 %9f width 9, default precision
62 %.2f default width, precision 2
63 %9.2f width 9, precision 2
64 %9.f width 9, precision 0
66 Width and precision are measured in units of Unicode code points.
67 (This differs from C's printf where the units are numbers
68 of bytes.) Either or both of the flags may be replaced with the
69 character '*', causing their values to be obtained from the next
70 operand, which must be of type int.
72 For most values, width is the minimum number of characters to output,
73 padding the formatted form with spaces if necessary.
74 For strings, precision is the maximum number of characters to output,
75 truncating if necessary.
77 For floating-point values, width sets the minimum width of the field and
78 precision sets the number of places after the decimal, if appropriate,
79 except that for %g/%G it sets the total number of digits. For example,
80 given 123.45 the format %6.2f prints 123.45 while %.4g prints 123.5.
81 The default precision for %e and %f is 6; for %g it is the smallest
82 number of digits necessary to identify the value uniquely.
84 For complex numbers, the width and precision apply to the two
85 components independently and the result is parenthesized, so %f applied
86 to 1.2+3.4i produces (1.200000+3.400000i).
88 Other flags:
89 + always print a sign for numeric values;
90 guarantee ASCII-only output for %q (%+q)
91 - pad with spaces on the right rather than the left (left-justify the field)
92 # alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
93 0X for hex (%#X); suppress 0x for %p (%#p);
94 for %q, print a raw (backquoted) string if strconv.CanBackquote
95 returns true;
96 write e.g. U+0078 'x' if the character is printable for %U (%#U).
97 ' ' (space) leave a space for elided sign in numbers (% d);
98 put spaces between bytes printing strings or slices in hex (% x, % X)
99 0 pad with leading zeros rather than spaces;
100 for numbers, this moves the padding after the sign
102 Flags are ignored by verbs that do not expect them.
103 For example there is no alternate decimal format, so %#d and %d
104 behave identically.
106 For each Printf-like function, there is also a Print function
107 that takes no format and is equivalent to saying %v for every
108 operand. Another variant Println inserts blanks between
109 operands and appends a newline.
111 Regardless of the verb, if an operand is an interface value,
112 the internal concrete value is used, not the interface itself.
113 Thus:
114 var i interface{} = 23
115 fmt.Printf("%v\n", i)
116 will print 23.
118 Except when printed using the verbs %T and %p, special
119 formatting considerations apply for operands that implement
120 certain interfaces. In order of application:
122 1. If an operand implements the Formatter interface, it will
123 be invoked. Formatter provides fine control of formatting.
125 2. If the %v verb is used with the # flag (%#v) and the operand
126 implements the GoStringer interface, that will be invoked.
128 If the format (which is implicitly %v for Println etc.) is valid
129 for a string (%s %q %v %x %X), the following two rules apply:
131 3. If an operand implements the error interface, the Error method
132 will be invoked to convert the object to a string, which will then
133 be formatted as required by the verb (if any).
135 4. If an operand implements method String() string, that method
136 will be invoked to convert the object to a string, which will then
137 be formatted as required by the verb (if any).
139 For compound operands such as slices and structs, the format
140 applies to the elements of each operand, recursively, not to the
141 operand as a whole. Thus %q will quote each element of a slice
142 of strings, and %6.2f will control formatting for each element
143 of a floating-point array.
145 To avoid recursion in cases such as
146 type X string
147 func (x X) String() string { return Sprintf("<%s>", x) }
148 convert the value before recurring:
149 func (x X) String() string { return Sprintf("<%s>", string(x)) }
151 Explicit argument indexes:
153 In Printf, Sprintf, and Fprintf, the default behavior is for each
154 formatting verb to format successive arguments passed in the call.
155 However, the notation [n] immediately before the verb indicates that the
156 nth one-indexed argument is to be formatted instead. The same notation
157 before a '*' for a width or precision selects the argument index holding
158 the value. After processing a bracketed expression [n], arguments n+1,
159 n+2, etc. will be processed unless otherwise directed.
161 For example,
162 fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
163 will yield "22, 11", while
164 fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6),
165 equivalent to
166 fmt.Sprintf("%6.2f", 12.0),
167 will yield " 12.00". Because an explicit index affects subsequent verbs,
168 this notation can be used to print the same values multiple times
169 by resetting the index for the first argument to be repeated:
170 fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
171 will yield "16 17 0x10 0x11".
173 Format errors:
175 If an invalid argument is given for a verb, such as providing
176 a string to %d, the generated string will contain a
177 description of the problem, as in these examples:
179 Wrong type or unknown verb: %!verb(type=value)
180 Printf("%d", hi): %!d(string=hi)
181 Too many arguments: %!(EXTRA type=value)
182 Printf("hi", "guys"): hi%!(EXTRA string=guys)
183 Too few arguments: %!verb(MISSING)
184 Printf("hi%d"): hi %!d(MISSING)
185 Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
186 Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi
187 Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
188 Invalid or invalid use of argument index: %!(BADINDEX)
189 Printf("%*[2]d", 7): %!d(BADINDEX)
190 Printf("%.[2]d", 7): %!d(BADINDEX)
192 All errors begin with the string "%!" followed sometimes
193 by a single character (the verb) and end with a parenthesized
194 description.
196 If an Error or String method triggers a panic when called by a
197 print routine, the fmt package reformats the error message
198 from the panic, decorating it with an indication that it came
199 through the fmt package. For example, if a String method
200 calls panic("bad"), the resulting formatted message will look
201 like
202 %!s(PANIC=bad)
204 The %!s just shows the print verb in use when the failure
205 occurred.
207 Scanning
209 An analogous set of functions scans formatted text to yield
210 values. Scan, Scanf and Scanln read from os.Stdin; Fscan,
211 Fscanf and Fscanln read from a specified io.Reader; Sscan,
212 Sscanf and Sscanln read from an argument string. Scanln,
213 Fscanln and Sscanln stop scanning at a newline and require that
214 the items be followed by one; Scanf, Fscanf and Sscanf require
215 newlines in the input to match newlines in the format; the other
216 routines treat newlines as spaces.
218 Scanf, Fscanf, and Sscanf parse the arguments according to a
219 format string, analogous to that of Printf. For example, %x
220 will scan an integer as a hexadecimal number, and %v will scan
221 the default representation format for the value.
223 The formats behave analogously to those of Printf with the
224 following exceptions:
226 %p is not implemented
227 %T is not implemented
228 %e %E %f %F %g %G are all equivalent and scan any floating point or complex value
229 %s and %v on strings scan a space-delimited token
230 Flags # and + are not implemented.
232 The familiar base-setting prefixes 0 (octal) and 0x
233 (hexadecimal) are accepted when scanning integers without a
234 format or with the %v verb.
236 Width is interpreted in the input text (%5s means at most
237 five runes of input will be read to scan a string) but there
238 is no syntax for scanning with a precision (no %5.2f, just
239 %5f).
241 When scanning with a format, all non-empty runs of space
242 characters (except newline) are equivalent to a single
243 space in both the format and the input. With that proviso,
244 text in the format string must match the input text; scanning
245 stops if it does not, with the return value of the function
246 indicating the number of arguments scanned.
248 In all the scanning functions, a carriage return followed
249 immediately by a newline is treated as a plain newline
250 (\r\n means the same as \n).
252 In all the scanning functions, if an operand implements method
253 Scan (that is, it implements the Scanner interface) that
254 method will be used to scan the text for that operand. Also,
255 if the number of arguments scanned is less than the number of
256 arguments provided, an error is returned.
258 All arguments to be scanned must be either pointers to basic
259 types or implementations of the Scanner interface.
261 Note: Fscan etc. can read one character (rune) past the input
262 they return, which means that a loop calling a scan routine
263 may skip some of the input. This is usually a problem only
264 when there is no space between input values. If the reader
265 provided to Fscan implements ReadRune, that method will be used
266 to read characters. If the reader also implements UnreadRune,
267 that method will be used to save the character and successive
268 calls will not lose data. To attach ReadRune and UnreadRune
269 methods to a reader without that capability, use
270 bufio.NewReader.
272 package fmt