]>
Commit | Line | Data |
---|---|---|
ff7c6d11 | 1 | //! Utilities for formatting and printing `String`s. |
1a4d82fc | 2 | //! |
3b2f2976 | 3 | //! This module contains the runtime support for the [`format!`] syntax extension. |
1a4d82fc | 4 | //! This macro is implemented in the compiler to emit calls to this module in |
3157f602 | 5 | //! order to format arguments at runtime into strings. |
1a4d82fc | 6 | //! |
c34b1796 | 7 | //! # Usage |
1a4d82fc | 8 | //! |
3b2f2976 XL |
9 | //! The [`format!`] macro is intended to be familiar to those coming from C's |
10 | //! `printf`/`fprintf` functions or Python's `str.format` function. | |
1a4d82fc | 11 | //! |
3b2f2976 | 12 | //! Some examples of the [`format!`] extension are: |
1a4d82fc | 13 | //! |
85aaf69f SL |
14 | //! ``` |
15 | //! format!("Hello"); // => "Hello" | |
16 | //! format!("Hello, {}!", "world"); // => "Hello, world!" | |
17 | //! format!("The number is {}", 1); // => "The number is 1" | |
18 | //! format!("{:?}", (3, 4)); // => "(3, 4)" | |
19 | //! format!("{value}", value=4); // => "4" | |
3c0e092e XL |
20 | //! let people = "Rustaceans"; |
21 | //! format!("Hello {people}!"); // => "Hello Rustaceans!" | |
85aaf69f | 22 | //! format!("{} {}", 1, 2); // => "1 2" |
3157f602 | 23 | //! format!("{:04}", 42); // => "0042" with leading zeros |
cdc7bbd5 XL |
24 | //! format!("{:#?}", (100, 200)); // => "( |
25 | //! // 100, | |
26 | //! // 200, | |
27 | //! // )" | |
1a4d82fc JJ |
28 | //! ``` |
29 | //! | |
30 | //! From these, you can see that the first argument is a format string. It is | |
31 | //! required by the compiler for this to be a string literal; it cannot be a | |
32 | //! variable passed in (in order to perform validity checking). The compiler | |
33 | //! will then parse the format string and determine if the list of arguments | |
34 | //! provided is suitable to pass to this format string. | |
35 | //! | |
9fa01778 | 36 | //! To convert a single value to a string, use the [`to_string`] method. This |
0731742a XL |
37 | //! will use the [`Display`] formatting trait. |
38 | //! | |
c34b1796 | 39 | //! ## Positional parameters |
1a4d82fc JJ |
40 | //! |
41 | //! Each formatting argument is allowed to specify which value argument it's | |
42 | //! referencing, and if omitted it is assumed to be "the next argument". For | |
43 | //! example, the format string `{} {} {}` would take three parameters, and they | |
44 | //! would be formatted in the same order as they're given. The format string | |
45 | //! `{2} {1} {0}`, however, would format arguments in reverse order. | |
46 | //! | |
47 | //! Things can get a little tricky once you start intermingling the two types of | |
48 | //! positional specifiers. The "next argument" specifier can be thought of as an | |
49 | //! iterator over the argument. Each time a "next argument" specifier is seen, | |
50 | //! the iterator advances. This leads to behavior like this: | |
51 | //! | |
c34b1796 | 52 | //! ``` |
85aaf69f | 53 | //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" |
1a4d82fc JJ |
54 | //! ``` |
55 | //! | |
56 | //! The internal iterator over the argument has not been advanced by the time | |
57 | //! the first `{}` is seen, so it prints the first argument. Then upon reaching | |
58 | //! the second `{}`, the iterator has advanced forward to the second argument. | |
f9f354fc XL |
59 | //! Essentially, parameters that explicitly name their argument do not affect |
60 | //! parameters that do not name an argument in terms of positional specifiers. | |
1a4d82fc JJ |
61 | //! |
62 | //! A format string is required to use all of its arguments, otherwise it is a | |
63 | //! compile-time error. You may refer to the same argument more than once in the | |
8bb4bdeb | 64 | //! format string. |
1a4d82fc | 65 | //! |
c34b1796 | 66 | //! ## Named parameters |
1a4d82fc JJ |
67 | //! |
68 | //! Rust itself does not have a Python-like equivalent of named parameters to a | |
f9f354fc | 69 | //! function, but the [`format!`] macro is a syntax extension that allows it to |
1a4d82fc JJ |
70 | //! leverage named parameters. Named parameters are listed at the end of the |
71 | //! argument list and have the syntax: | |
72 | //! | |
73 | //! ```text | |
74 | //! identifier '=' expression | |
75 | //! ``` | |
76 | //! | |
5099ac24 | 77 | //! For example, the following [`format!`] expressions all use named arguments: |
1a4d82fc | 78 | //! |
85aaf69f | 79 | //! ``` |
1a4d82fc | 80 | //! format!("{argument}", argument = "test"); // => "test" |
a7813a04 | 81 | //! format!("{name} {}", 1, name = 2); // => "2 1" |
85aaf69f | 82 | //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" |
1a4d82fc JJ |
83 | //! ``` |
84 | //! | |
3c0e092e XL |
85 | //! If a named parameter does not appear in the argument list, `format!` will |
86 | //! reference a variable with that name in the current scope. | |
87 | //! | |
88 | //! ``` | |
89 | //! let argument = 2 + 2; | |
90 | //! format!("{argument}"); // => "4" | |
91 | //! | |
92 | //! fn make_string(a: u32, b: &str) -> String { | |
93 | //! format!("{b} {a}") | |
94 | //! } | |
95 | //! make_string(927, "label"); // => "label 927" | |
96 | //! ``` | |
97 | //! | |
c1a9b12d | 98 | //! It is not valid to put positional parameters (those without names) after |
f9f354fc | 99 | //! arguments that have names. Like with positional parameters, it is not |
c1a9b12d | 100 | //! valid to provide named parameters that are unused by the format string. |
1a4d82fc | 101 | //! |
e74abb32 XL |
102 | //! # Formatting Parameters |
103 | //! | |
104 | //! Each argument being formatted can be transformed by a number of formatting | |
3dfed10e | 105 | //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These |
e74abb32 XL |
106 | //! parameters affect the string representation of what's being formatted. |
107 | //! | |
108 | //! ## Width | |
109 | //! | |
110 | //! ``` | |
111 | //! // All of these print "Hello x !" | |
112 | //! println!("Hello {:5}!", "x"); | |
113 | //! println!("Hello {:1$}!", "x", 5); | |
114 | //! println!("Hello {1:0$}!", 5, "x"); | |
115 | //! println!("Hello {:width$}!", "x", width = 5); | |
3c0e092e XL |
116 | //! let width = 5; |
117 | //! println!("Hello {:width$}!", "x"); | |
e74abb32 XL |
118 | //! ``` |
119 | //! | |
120 | //! This is a parameter for the "minimum width" that the format should take up. | |
121 | //! If the value's string does not fill up this many characters, then the | |
122 | //! padding specified by fill/alignment will be used to take up the required | |
123 | //! space (see below). | |
124 | //! | |
125 | //! The value for the width can also be provided as a [`usize`] in the list of | |
126 | //! parameters by adding a postfix `$`, indicating that the second argument is | |
127 | //! a [`usize`] specifying the width. | |
128 | //! | |
129 | //! Referring to an argument with the dollar syntax does not affect the "next | |
130 | //! argument" counter, so it's usually a good idea to refer to arguments by | |
131 | //! position, or use named arguments. | |
132 | //! | |
133 | //! ## Fill/Alignment | |
134 | //! | |
135 | //! ``` | |
136 | //! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); | |
137 | //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); | |
138 | //! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); | |
139 | //! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); | |
140 | //! ``` | |
141 | //! | |
142 | //! The optional fill character and alignment is provided normally in conjunction with the | |
143 | //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`. | |
144 | //! This indicates that if the value being formatted is smaller than | |
145 | //! `width` some extra characters will be printed around it. | |
146 | //! Filling comes in the following variants for different alignments: | |
147 | //! | |
148 | //! * `[fill]<` - the argument is left-aligned in `width` columns | |
149 | //! * `[fill]^` - the argument is center-aligned in `width` columns | |
150 | //! * `[fill]>` - the argument is right-aligned in `width` columns | |
151 | //! | |
152 | //! The default [fill/alignment](#fillalignment) for non-numerics is a space and | |
153 | //! left-aligned. The | |
f9f354fc | 154 | //! default for numeric formatters is also a space character but with right-alignment. If |
e74abb32 XL |
155 | //! the `0` flag (see below) is specified for numerics, then the implicit fill character is |
156 | //! `0`. | |
157 | //! | |
94222f64 | 158 | //! Note that alignment might not be implemented by some types. In particular, it |
e74abb32 XL |
159 | //! is not generally implemented for the `Debug` trait. A good way to ensure |
160 | //! padding is applied is to format your input, then pad this resulting string | |
161 | //! to obtain your output: | |
162 | //! | |
163 | //! ``` | |
164 | //! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !" | |
165 | //! ``` | |
166 | //! | |
167 | //! ## Sign/`#`/`0` | |
168 | //! | |
169 | //! ``` | |
170 | //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); | |
171 | //! assert_eq!(format!("{:#x}!", 27), "0x1b!"); | |
172 | //! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); | |
173 | //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); | |
174 | //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); | |
175 | //! ``` | |
176 | //! | |
177 | //! These are all flags altering the behavior of the formatter. | |
178 | //! | |
179 | //! * `+` - This is intended for numeric types and indicates that the sign | |
180 | //! should always be printed. Positive signs are never printed by | |
cdc7bbd5 XL |
181 | //! default, and the negative sign is only printed by default for signed values. |
182 | //! This flag indicates that the correct sign (`+` or `-`) should always be printed. | |
e74abb32 | 183 | //! * `-` - Currently not used |
f9f354fc | 184 | //! * `#` - This flag indicates that the "alternate" form of printing should |
e74abb32 | 185 | //! be used. The alternate forms are: |
cdc7bbd5 | 186 | //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation) |
e74abb32 XL |
187 | //! * `#x` - precedes the argument with a `0x` |
188 | //! * `#X` - precedes the argument with a `0x` | |
189 | //! * `#b` - precedes the argument with a `0b` | |
190 | //! * `#o` - precedes the argument with a `0o` | |
191 | //! * `0` - This is used to indicate for integer formats that the padding to `width` should | |
192 | //! both be done with a `0` character as well as be sign-aware. A format | |
193 | //! like `{:08}` would yield `00000001` for the integer `1`, while the | |
194 | //! same format would yield `-0000001` for the integer `-1`. Notice that | |
195 | //! the negative version has one fewer zero than the positive version. | |
f9f354fc | 196 | //! Note that padding zeros are always placed after the sign (if any) |
e74abb32 | 197 | //! and before the digits. When used together with the `#` flag, a similar |
f9f354fc | 198 | //! rule applies: padding zeros are inserted after the prefix but before |
e74abb32 XL |
199 | //! the digits. The prefix is included in the total width. |
200 | //! | |
201 | //! ## Precision | |
202 | //! | |
203 | //! For non-numeric types, this can be considered a "maximum width". If the resulting string is | |
204 | //! longer than this width, then it is truncated down to this many characters and that truncated | |
205 | //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. | |
206 | //! | |
207 | //! For integral types, this is ignored. | |
208 | //! | |
209 | //! For floating-point types, this indicates how many digits after the decimal point should be | |
210 | //! printed. | |
211 | //! | |
212 | //! There are three possible ways to specify the desired `precision`: | |
213 | //! | |
214 | //! 1. An integer `.N`: | |
215 | //! | |
216 | //! the integer `N` itself is the precision. | |
217 | //! | |
218 | //! 2. An integer or name followed by dollar sign `.N$`: | |
219 | //! | |
220 | //! use format *argument* `N` (which must be a `usize`) as the precision. | |
221 | //! | |
222 | //! 3. An asterisk `.*`: | |
223 | //! | |
224 | //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the | |
225 | //! first input holds the `usize` precision, and the second holds the value to print. Note that | |
226 | //! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers | |
227 | //! to the *value* to print, and the `precision` must come in the input preceding `<arg>`. | |
228 | //! | |
229 | //! For example, the following calls all print the same thing `Hello x is 0.01000`: | |
230 | //! | |
231 | //! ``` | |
232 | //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} | |
233 | //! println!("Hello {0} is {1:.5}", "x", 0.01); | |
234 | //! | |
235 | //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} | |
236 | //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01); | |
237 | //! | |
238 | //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} | |
239 | //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01); | |
240 | //! | |
241 | //! // Hello {next arg ("x")} is {second of next two args (0.01) with precision | |
242 | //! // specified in first of next two args (5)} | |
243 | //! println!("Hello {} is {:.*}", "x", 5, 0.01); | |
244 | //! | |
245 | //! // Hello {next arg ("x")} is {arg 2 (0.01) with precision | |
246 | //! // specified in its predecessor (5)} | |
247 | //! println!("Hello {} is {2:.*}", "x", 5, 0.01); | |
248 | //! | |
249 | //! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified | |
250 | //! // in arg "prec" (5)} | |
251 | //! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); | |
252 | //! ``` | |
1a4d82fc | 253 | //! |
e74abb32 | 254 | //! While these: |
c34b1796 AL |
255 | //! |
256 | //! ``` | |
e74abb32 XL |
257 | //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); |
258 | //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); | |
259 | //! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); | |
260 | //! ``` | |
c34b1796 | 261 | //! |
3dfed10e | 262 | //! print three significantly different things: |
e74abb32 XL |
263 | //! |
264 | //! ```text | |
265 | //! Hello, `1234.560` has 3 fractional digits | |
266 | //! Hello, `123` has 3 characters | |
267 | //! Hello, ` 123` has 3 right-aligned characters | |
c34b1796 AL |
268 | //! ``` |
269 | //! | |
74b04a01 XL |
270 | //! ## Localization |
271 | //! | |
272 | //! In some programming languages, the behavior of string formatting functions | |
273 | //! depends on the operating system's locale setting. The format functions | |
f9f354fc | 274 | //! provided by Rust's standard library do not have any concept of locale and |
74b04a01 XL |
275 | //! will produce the same results on all systems regardless of user |
276 | //! configuration. | |
277 | //! | |
278 | //! For example, the following code will always print `1.5` even if the system | |
279 | //! locale uses a decimal separator other than a dot. | |
280 | //! | |
281 | //! ``` | |
282 | //! println!("The value is {}", 1.5); | |
283 | //! ``` | |
284 | //! | |
e74abb32 XL |
285 | //! # Escaping |
286 | //! | |
287 | //! The literal characters `{` and `}` may be included in a string by preceding | |
288 | //! them with the same character. For example, the `{` character is escaped with | |
289 | //! `{{` and the `}` character is escaped with `}}`. | |
1a4d82fc | 290 | //! |
e74abb32 XL |
291 | //! ``` |
292 | //! assert_eq!(format!("Hello {{}}"), "Hello {}"); | |
293 | //! assert_eq!(format!("{{ Hello"), "{ Hello"); | |
294 | //! ``` | |
295 | //! | |
296 | //! # Syntax | |
297 | //! | |
298 | //! To summarize, here you can find the full grammar of format strings. | |
299 | //! The syntax for the formatting language used is drawn from other languages, | |
300 | //! so it should not be too alien. Arguments are formatted with Python-like | |
301 | //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like | |
302 | //! `%`. The actual grammar for the formatting syntax is: | |
303 | //! | |
304 | //! ```text | |
5869c6ff XL |
305 | //! format_string := text [ maybe_format text ] * |
306 | //! maybe_format := '{' '{' | '}' '}' | format | |
e74abb32 XL |
307 | //! format := '{' [ argument ] [ ':' format_spec ] '}' |
308 | //! argument := integer | identifier | |
309 | //! | |
5869c6ff | 310 | //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type |
e74abb32 XL |
311 | //! fill := character |
312 | //! align := '<' | '^' | '>' | |
313 | //! sign := '+' | '-' | |
314 | //! width := count | |
315 | //! precision := count | '*' | |
5869c6ff | 316 | //! type := '' | '?' | 'x?' | 'X?' | identifier |
e74abb32 XL |
317 | //! count := parameter | integer |
318 | //! parameter := argument '$' | |
319 | //! ``` | |
94222f64 | 320 | //! In the above grammar, `text` must not contain any `'{'` or `'}'` characters. |
e74abb32 XL |
321 | //! |
322 | //! # Formatting traits | |
1a4d82fc JJ |
323 | //! |
324 | //! When requesting that an argument be formatted with a particular type, you | |
325 | //! are actually requesting that an argument ascribes to a particular trait. | |
3b2f2976 | 326 | //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as |
9fa01778 | 327 | //! well as [`isize`]). The current mapping of types to traits is: |
1a4d82fc | 328 | //! |
3b2f2976 XL |
329 | //! * *nothing* ⇒ [`Display`] |
330 | //! * `?` ⇒ [`Debug`] | |
0531ce1d XL |
331 | //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers |
332 | //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers | |
29967ef6 XL |
333 | //! * `o` ⇒ [`Octal`] |
334 | //! * `x` ⇒ [`LowerHex`] | |
335 | //! * `X` ⇒ [`UpperHex`] | |
336 | //! * `p` ⇒ [`Pointer`] | |
3b2f2976 | 337 | //! * `b` ⇒ [`Binary`] |
29967ef6 XL |
338 | //! * `e` ⇒ [`LowerExp`] |
339 | //! * `E` ⇒ [`UpperExp`] | |
1a4d82fc JJ |
340 | //! |
341 | //! What this means is that any type of argument which implements the | |
3b2f2976 | 342 | //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations |
1a4d82fc JJ |
343 | //! are provided for these traits for a number of primitive types by the |
344 | //! standard library as well. If no format is specified (as in `{}` or `{:6}`), | |
3b2f2976 | 345 | //! then the format trait used is the [`Display`] trait. |
1a4d82fc JJ |
346 | //! |
347 | //! When implementing a format trait for your own type, you will have to | |
348 | //! implement a method of the signature: | |
349 | //! | |
c34b1796 | 350 | //! ``` |
92a42be0 | 351 | //! # #![allow(dead_code)] |
1a4d82fc JJ |
352 | //! # use std::fmt; |
353 | //! # struct Foo; // our custom type | |
85aaf69f SL |
354 | //! # impl fmt::Display for Foo { |
355 | //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
1a4d82fc JJ |
356 | //! # write!(f, "testing, testing") |
357 | //! # } } | |
358 | //! ``` | |
359 | //! | |
360 | //! Your type will be passed as `self` by-reference, and then the function | |
361 | //! should emit output into the `f.buf` stream. It is up to each format trait | |
362 | //! implementation to correctly adhere to the requested formatting parameters. | |
363 | //! The values of these parameters will be listed in the fields of the | |
3b2f2976 | 364 | //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also |
1a4d82fc JJ |
365 | //! provides some helper methods. |
366 | //! | |
3b2f2976 | 367 | //! Additionally, the return value of this function is [`fmt::Result`] which is a |
c295e0f8 | 368 | //! type alias of <code>[Result]<(), [std::fmt::Error]></code>. Formatting implementations |
dfeec247 | 369 | //! should ensure that they propagate errors from the [`Formatter`] (e.g., when |
0bf4aa26 | 370 | //! calling [`write!`]). However, they should never return errors spuriously. That |
9e0c209e | 371 | //! is, a formatting implementation must and may only return an error if the |
3b2f2976 | 372 | //! passed-in [`Formatter`] returns an error. This is because, contrary to what |
9e0c209e SL |
373 | //! the function signature might suggest, string formatting is an infallible |
374 | //! operation. This function only returns a result because writing to the | |
375 | //! underlying stream might fail and it must provide a way to propagate the fact | |
376 | //! that an error has occurred back up the stack. | |
1a4d82fc JJ |
377 | //! |
378 | //! An example of implementing the formatting traits would look | |
379 | //! like: | |
380 | //! | |
c34b1796 | 381 | //! ``` |
1a4d82fc | 382 | //! use std::fmt; |
1a4d82fc | 383 | //! |
85aaf69f | 384 | //! #[derive(Debug)] |
1a4d82fc | 385 | //! struct Vector2D { |
85aaf69f SL |
386 | //! x: isize, |
387 | //! y: isize, | |
1a4d82fc JJ |
388 | //! } |
389 | //! | |
85aaf69f | 390 | //! impl fmt::Display for Vector2D { |
1a4d82fc | 391 | //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
85aaf69f | 392 | //! // The `f` value implements the `Write` trait, which is what the |
1a4d82fc JJ |
393 | //! // write! macro is expecting. Note that this formatting ignores the |
394 | //! // various flags provided to format strings. | |
395 | //! write!(f, "({}, {})", self.x, self.y) | |
396 | //! } | |
397 | //! } | |
398 | //! | |
399 | //! // Different traits allow different forms of output of a type. The meaning | |
400 | //! // of this format is to print the magnitude of a vector. | |
401 | //! impl fmt::Binary for Vector2D { | |
402 | //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
403 | //! let magnitude = (self.x * self.x + self.y * self.y) as f64; | |
404 | //! let magnitude = magnitude.sqrt(); | |
405 | //! | |
406 | //! // Respect the formatting flags by using the helper method | |
9346a6ac AL |
407 | //! // `pad_integral` on the Formatter object. See the method |
408 | //! // documentation for details, and the function `pad` can be used | |
409 | //! // to pad strings. | |
1a4d82fc | 410 | //! let decimals = f.precision().unwrap_or(3); |
9346a6ac | 411 | //! let string = format!("{:.*}", decimals, magnitude); |
c34b1796 | 412 | //! f.pad_integral(true, "", &string) |
1a4d82fc JJ |
413 | //! } |
414 | //! } | |
415 | //! | |
416 | //! fn main() { | |
417 | //! let myvector = Vector2D { x: 3, y: 4 }; | |
418 | //! | |
ee023bcb FG |
419 | //! println!("{myvector}"); // => "(3, 4)" |
420 | //! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}" | |
421 | //! println!("{myvector:10.3b}"); // => " 5.000" | |
1a4d82fc JJ |
422 | //! } |
423 | //! ``` | |
424 | //! | |
b039eaaf | 425 | //! ### `fmt::Display` vs `fmt::Debug` |
1a4d82fc JJ |
426 | //! |
427 | //! These two formatting traits have distinct purposes: | |
428 | //! | |
3b2f2976 | 429 | //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully |
1a4d82fc | 430 | //! represented as a UTF-8 string at all times. It is **not** expected that |
3b2f2976 XL |
431 | //! all types implement the [`Display`] trait. |
432 | //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types. | |
1a4d82fc | 433 | //! Output will typically represent the internal state as faithfully as possible. |
3b2f2976 | 434 | //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In |
85aaf69f | 435 | //! most cases, using `#[derive(Debug)]` is sufficient and recommended. |
1a4d82fc JJ |
436 | //! |
437 | //! Some examples of the output from both traits: | |
438 | //! | |
439 | //! ``` | |
c34b1796 | 440 | //! assert_eq!(format!("{} {:?}", 3, 4), "3 4"); |
1a4d82fc JJ |
441 | //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); |
442 | //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); | |
443 | //! ``` | |
444 | //! | |
e74abb32 | 445 | //! # Related macros |
1a4d82fc | 446 | //! |
3b2f2976 | 447 | //! There are a number of related macros in the [`format!`] family. The ones that |
1a4d82fc JJ |
448 | //! are currently implemented are: |
449 | //! | |
041b39d2 | 450 | //! ```ignore (only-for-syntax-highlight) |
1a4d82fc | 451 | //! format! // described above |
9346a6ac | 452 | //! write! // first argument is a &mut io::Write, the destination |
1a4d82fc JJ |
453 | //! writeln! // same as write but appends a newline |
454 | //! print! // the format string is printed to the standard output | |
455 | //! println! // same as print but appends a newline | |
ff7c6d11 XL |
456 | //! eprint! // the format string is printed to the standard error |
457 | //! eprintln! // same as eprint but appends a newline | |
1a4d82fc JJ |
458 | //! format_args! // described below. |
459 | //! ``` | |
460 | //! | |
c34b1796 | 461 | //! ### `write!` |
1a4d82fc | 462 | //! |
3b2f2976 | 463 | //! This and [`writeln!`] are two macros which are used to emit the format string |
1a4d82fc JJ |
464 | //! to a specified stream. This is used to prevent intermediate allocations of |
465 | //! format strings and instead directly write the output. Under the hood, this | |
3b2f2976 XL |
466 | //! function is actually invoking the [`write_fmt`] function defined on the |
467 | //! [`std::io::Write`] trait. Example usage is: | |
1a4d82fc | 468 | //! |
c34b1796 | 469 | //! ``` |
1a4d82fc | 470 | //! # #![allow(unused_must_use)] |
c34b1796 | 471 | //! use std::io::Write; |
1a4d82fc | 472 | //! let mut w = Vec::new(); |
85aaf69f | 473 | //! write!(&mut w, "Hello {}!", "world"); |
1a4d82fc JJ |
474 | //! ``` |
475 | //! | |
c34b1796 | 476 | //! ### `print!` |
1a4d82fc | 477 | //! |
3b2f2976 | 478 | //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`] |
1a4d82fc JJ |
479 | //! macro, the goal of these macros is to avoid intermediate allocations when |
480 | //! printing output. Example usage is: | |
481 | //! | |
c34b1796 | 482 | //! ``` |
1a4d82fc JJ |
483 | //! print!("Hello {}!", "world"); |
484 | //! println!("I have a newline {}", "character at the end"); | |
485 | //! ``` | |
ff7c6d11 XL |
486 | //! ### `eprint!` |
487 | //! | |
488 | //! The [`eprint!`] and [`eprintln!`] macros are identical to | |
489 | //! [`print!`] and [`println!`], respectively, except they emit their | |
490 | //! output to stderr. | |
1a4d82fc | 491 | //! |
c34b1796 AL |
492 | //! ### `format_args!` |
493 | //! | |
f9f354fc | 494 | //! This is a curious macro used to safely pass around |
1a4d82fc JJ |
495 | //! an opaque object describing the format string. This object |
496 | //! does not require any heap allocations to create, and it only | |
497 | //! references information on the stack. Under the hood, all of | |
498 | //! the related macros are implemented in terms of this. First | |
499 | //! off, some example usage is: | |
500 | //! | |
501 | //! ``` | |
92a42be0 | 502 | //! # #![allow(unused_must_use)] |
1a4d82fc | 503 | //! use std::fmt; |
c34b1796 | 504 | //! use std::io::{self, Write}; |
1a4d82fc | 505 | //! |
c34b1796 | 506 | //! let mut some_writer = io::stdout(); |
85aaf69f | 507 | //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); |
1a4d82fc JJ |
508 | //! |
509 | //! fn my_fmt_fn(args: fmt::Arguments) { | |
c34b1796 | 510 | //! write!(&mut io::stdout(), "{}", args); |
1a4d82fc | 511 | //! } |
a7813a04 | 512 | //! my_fmt_fn(format_args!(", or a {} too", "function")); |
1a4d82fc JJ |
513 | //! ``` |
514 | //! | |
3b2f2976 XL |
515 | //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`]. |
516 | //! This structure can then be passed to the [`write`] and [`format`] functions | |
1a4d82fc JJ |
517 | //! inside this module in order to process the format string. |
518 | //! The goal of this macro is to even further prevent intermediate allocations | |
f9f354fc | 519 | //! when dealing with formatting strings. |
1a4d82fc JJ |
520 | //! |
521 | //! For example, a logging library could use the standard formatting syntax, but | |
522 | //! it would internally pass around this structure until it has been determined | |
523 | //! where output should go to. | |
524 | //! | |
c295e0f8 XL |
525 | //! [`fmt::Result`]: Result "fmt::Result" |
526 | //! [Result]: core::result::Result "std::result::Result" | |
527 | //! [std::fmt::Error]: Error "fmt::Error" | |
528 | //! [`write`]: write() "fmt::write" | |
529 | //! [`to_string`]: crate::string::ToString::to_string "ToString::to_string" | |
3b2f2976 XL |
530 | //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt |
531 | //! [`std::io::Write`]: ../../std/io/trait.Write.html | |
c295e0f8 XL |
532 | //! [`print!`]: ../../std/macro.print.html "print!" |
533 | //! [`println!`]: ../../std/macro.println.html "println!" | |
534 | //! [`eprint!`]: ../../std/macro.eprint.html "eprint!" | |
535 | //! [`eprintln!`]: ../../std/macro.eprintln.html "eprintln!" | |
536 | //! [`fmt::Arguments`]: Arguments "fmt::Arguments" | |
537 | //! [`format`]: format() "fmt::format" | |
1a4d82fc | 538 | |
85aaf69f | 539 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 540 | |
dfeec247 | 541 | #[unstable(feature = "fmt_internals", issue = "none")] |
92a42be0 | 542 | pub use core::fmt::rt; |
60c5eb7d XL |
543 | #[stable(feature = "fmt_flags_align", since = "1.28.0")] |
544 | pub use core::fmt::Alignment; | |
92a42be0 | 545 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
546 | pub use core::fmt::Error; |
547 | #[stable(feature = "rust1", since = "1.0.0")] | |
548 | pub use core::fmt::{write, ArgumentV1, Arguments}; | |
92a42be0 | 549 | #[stable(feature = "rust1", since = "1.0.0")] |
0531ce1d | 550 | pub use core::fmt::{Binary, Octal}; |
92a42be0 | 551 | #[stable(feature = "rust1", since = "1.0.0")] |
0531ce1d | 552 | pub use core::fmt::{Debug, Display}; |
92a42be0 | 553 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d | 554 | pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; |
92a42be0 | 555 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d | 556 | pub use core::fmt::{Formatter, Result, Write}; |
92a42be0 | 557 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d | 558 | pub use core::fmt::{LowerExp, UpperExp}; |
92a42be0 | 559 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d | 560 | pub use core::fmt::{LowerHex, Pointer, UpperHex}; |
1a4d82fc | 561 | |
17df50a5 | 562 | #[cfg(not(no_global_oom_handling))] |
9fa01778 | 563 | use crate::string; |
1a4d82fc | 564 | |
3b2f2976 | 565 | /// The `format` function takes an [`Arguments`] struct and returns the resulting |
041b39d2 | 566 | /// formatted string. |
1a4d82fc | 567 | /// |
3b2f2976 | 568 | /// The [`Arguments`] instance can be created with the [`format_args!`] macro. |
1a4d82fc | 569 | /// |
c34b1796 | 570 | /// # Examples |
1a4d82fc | 571 | /// |
a7813a04 XL |
572 | /// Basic usage: |
573 | /// | |
c34b1796 | 574 | /// ``` |
1a4d82fc JJ |
575 | /// use std::fmt; |
576 | /// | |
577 | /// let s = fmt::format(format_args!("Hello, {}!", "world")); | |
a7813a04 XL |
578 | /// assert_eq!(s, "Hello, world!"); |
579 | /// ``` | |
580 | /// | |
ff7c6d11 | 581 | /// Please note that using [`format!`] might be preferable. |
a7813a04 XL |
582 | /// Example: |
583 | /// | |
584 | /// ``` | |
585 | /// let s = format!("Hello, {}!", "world"); | |
586 | /// assert_eq!(s, "Hello, world!"); | |
1a4d82fc | 587 | /// ``` |
a7813a04 | 588 | /// |
3dfed10e XL |
589 | /// [`format_args!`]: core::format_args |
590 | /// [`format!`]: crate::format | |
17df50a5 | 591 | #[cfg(not(no_global_oom_handling))] |
3c0e092e | 592 | #[must_use] |
85aaf69f | 593 | #[stable(feature = "rust1", since = "1.0.0")] |
9fa01778 | 594 | pub fn format(args: Arguments<'_>) -> string::String { |
8bb4bdeb XL |
595 | let capacity = args.estimated_capacity(); |
596 | let mut output = string::String::with_capacity(capacity); | |
60c5eb7d | 597 | output.write_fmt(args).expect("a formatting trait implementation returned an error"); |
1a4d82fc JJ |
598 | output |
599 | } |