1 //! Utilities for formatting and printing `String`s.
3 //! This module contains the runtime support for the [`format!`] syntax extension.
4 //! This macro is implemented in the compiler to emit calls to this module in
5 //! order to format arguments at runtime into strings.
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.
12 //! Some examples of the [`format!`] extension are:
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"
20 //! format!("{} {}", 1, 2); // => "1 2"
21 //! format!("{:04}", 42); // => "0042" with leading zeros
22 //! format!("{:#?}", (100, 200)); // => "(
28 //! From these, you can see that the first argument is a format string. It is
29 //! required by the compiler for this to be a string literal; it cannot be a
30 //! variable passed in (in order to perform validity checking). The compiler
31 //! will then parse the format string and determine if the list of arguments
32 //! provided is suitable to pass to this format string.
34 //! To convert a single value to a string, use the [`to_string`] method. This
35 //! will use the [`Display`] formatting trait.
37 //! ## Positional parameters
39 //! Each formatting argument is allowed to specify which value argument it's
40 //! referencing, and if omitted it is assumed to be "the next argument". For
41 //! example, the format string `{} {} {}` would take three parameters, and they
42 //! would be formatted in the same order as they're given. The format string
43 //! `{2} {1} {0}`, however, would format arguments in reverse order.
45 //! Things can get a little tricky once you start intermingling the two types of
46 //! positional specifiers. The "next argument" specifier can be thought of as an
47 //! iterator over the argument. Each time a "next argument" specifier is seen,
48 //! the iterator advances. This leads to behavior like this:
51 //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
54 //! The internal iterator over the argument has not been advanced by the time
55 //! the first `{}` is seen, so it prints the first argument. Then upon reaching
56 //! the second `{}`, the iterator has advanced forward to the second argument.
57 //! Essentially, parameters that explicitly name their argument do not affect
58 //! parameters that do not name an argument in terms of positional specifiers.
60 //! A format string is required to use all of its arguments, otherwise it is a
61 //! compile-time error. You may refer to the same argument more than once in the
64 //! ## Named parameters
66 //! Rust itself does not have a Python-like equivalent of named parameters to a
67 //! function, but the [`format!`] macro is a syntax extension that allows it to
68 //! leverage named parameters. Named parameters are listed at the end of the
69 //! argument list and have the syntax:
72 //! identifier '=' expression
75 //! For example, the following [`format!`] expressions all use named argument:
78 //! format!("{argument}", argument = "test"); // => "test"
79 //! format!("{name} {}", 1, name = 2); // => "2 1"
80 //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
83 //! It is not valid to put positional parameters (those without names) after
84 //! arguments that have names. Like with positional parameters, it is not
85 //! valid to provide named parameters that are unused by the format string.
87 //! # Formatting Parameters
89 //! Each argument being formatted can be transformed by a number of formatting
90 //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These
91 //! parameters affect the string representation of what's being formatted.
96 //! // All of these print "Hello x !"
97 //! println!("Hello {:5}!", "x");
98 //! println!("Hello {:1$}!", "x", 5);
99 //! println!("Hello {1:0$}!", 5, "x");
100 //! println!("Hello {:width$}!", "x", width = 5);
103 //! This is a parameter for the "minimum width" that the format should take up.
104 //! If the value's string does not fill up this many characters, then the
105 //! padding specified by fill/alignment will be used to take up the required
106 //! space (see below).
108 //! The value for the width can also be provided as a [`usize`] in the list of
109 //! parameters by adding a postfix `$`, indicating that the second argument is
110 //! a [`usize`] specifying the width.
112 //! Referring to an argument with the dollar syntax does not affect the "next
113 //! argument" counter, so it's usually a good idea to refer to arguments by
114 //! position, or use named arguments.
116 //! ## Fill/Alignment
119 //! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !");
120 //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!");
121 //! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !");
122 //! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!");
125 //! The optional fill character and alignment is provided normally in conjunction with the
126 //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`.
127 //! This indicates that if the value being formatted is smaller than
128 //! `width` some extra characters will be printed around it.
129 //! Filling comes in the following variants for different alignments:
131 //! * `[fill]<` - the argument is left-aligned in `width` columns
132 //! * `[fill]^` - the argument is center-aligned in `width` columns
133 //! * `[fill]>` - the argument is right-aligned in `width` columns
135 //! The default [fill/alignment](#fillalignment) for non-numerics is a space and
136 //! left-aligned. The
137 //! default for numeric formatters is also a space character but with right-alignment. If
138 //! the `0` flag (see below) is specified for numerics, then the implicit fill character is
141 //! Note that alignment may not be implemented by some types. In particular, it
142 //! is not generally implemented for the `Debug` trait. A good way to ensure
143 //! padding is applied is to format your input, then pad this resulting string
144 //! to obtain your output:
147 //! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !"
153 //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!");
154 //! assert_eq!(format!("{:#x}!", 27), "0x1b!");
155 //! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!");
156 //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!");
157 //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!");
160 //! These are all flags altering the behavior of the formatter.
162 //! * `+` - This is intended for numeric types and indicates that the sign
163 //! should always be printed. Positive signs are never printed by
164 //! default, and the negative sign is only printed by default for signed values.
165 //! This flag indicates that the correct sign (`+` or `-`) should always be printed.
166 //! * `-` - Currently not used
167 //! * `#` - This flag indicates that the "alternate" form of printing should
168 //! be used. The alternate forms are:
169 //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
170 //! * `#x` - precedes the argument with a `0x`
171 //! * `#X` - precedes the argument with a `0x`
172 //! * `#b` - precedes the argument with a `0b`
173 //! * `#o` - precedes the argument with a `0o`
174 //! * `0` - This is used to indicate for integer formats that the padding to `width` should
175 //! both be done with a `0` character as well as be sign-aware. A format
176 //! like `{:08}` would yield `00000001` for the integer `1`, while the
177 //! same format would yield `-0000001` for the integer `-1`. Notice that
178 //! the negative version has one fewer zero than the positive version.
179 //! Note that padding zeros are always placed after the sign (if any)
180 //! and before the digits. When used together with the `#` flag, a similar
181 //! rule applies: padding zeros are inserted after the prefix but before
182 //! the digits. The prefix is included in the total width.
186 //! For non-numeric types, this can be considered a "maximum width". If the resulting string is
187 //! longer than this width, then it is truncated down to this many characters and that truncated
188 //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set.
190 //! For integral types, this is ignored.
192 //! For floating-point types, this indicates how many digits after the decimal point should be
195 //! There are three possible ways to specify the desired `precision`:
197 //! 1. An integer `.N`:
199 //! the integer `N` itself is the precision.
201 //! 2. An integer or name followed by dollar sign `.N$`:
203 //! use format *argument* `N` (which must be a `usize`) as the precision.
205 //! 3. An asterisk `.*`:
207 //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the
208 //! first input holds the `usize` precision, and the second holds the value to print. Note that
209 //! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers
210 //! to the *value* to print, and the `precision` must come in the input preceding `<arg>`.
212 //! For example, the following calls all print the same thing `Hello x is 0.01000`:
215 //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)}
216 //! println!("Hello {0} is {1:.5}", "x", 0.01);
218 //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)}
219 //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
221 //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)}
222 //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
224 //! // Hello {next arg ("x")} is {second of next two args (0.01) with precision
225 //! // specified in first of next two args (5)}
226 //! println!("Hello {} is {:.*}", "x", 5, 0.01);
228 //! // Hello {next arg ("x")} is {arg 2 (0.01) with precision
229 //! // specified in its predecessor (5)}
230 //! println!("Hello {} is {2:.*}", "x", 5, 0.01);
232 //! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified
233 //! // in arg "prec" (5)}
234 //! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
240 //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
241 //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
242 //! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
245 //! print three significantly different things:
248 //! Hello, `1234.560` has 3 fractional digits
249 //! Hello, `123` has 3 characters
250 //! Hello, ` 123` has 3 right-aligned characters
255 //! In some programming languages, the behavior of string formatting functions
256 //! depends on the operating system's locale setting. The format functions
257 //! provided by Rust's standard library do not have any concept of locale and
258 //! will produce the same results on all systems regardless of user
261 //! For example, the following code will always print `1.5` even if the system
262 //! locale uses a decimal separator other than a dot.
265 //! println!("The value is {}", 1.5);
270 //! The literal characters `{` and `}` may be included in a string by preceding
271 //! them with the same character. For example, the `{` character is escaped with
272 //! `{{` and the `}` character is escaped with `}}`.
275 //! assert_eq!(format!("Hello {{}}"), "Hello {}");
276 //! assert_eq!(format!("{{ Hello"), "{ Hello");
281 //! To summarize, here you can find the full grammar of format strings.
282 //! The syntax for the formatting language used is drawn from other languages,
283 //! so it should not be too alien. Arguments are formatted with Python-like
284 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
285 //! `%`. The actual grammar for the formatting syntax is:
288 //! format_string := text [ maybe_format text ] *
289 //! maybe_format := '{' '{' | '}' '}' | format
290 //! format := '{' [ argument ] [ ':' format_spec ] '}'
291 //! argument := integer | identifier
293 //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
294 //! fill := character
295 //! align := '<' | '^' | '>'
296 //! sign := '+' | '-'
298 //! precision := count | '*'
299 //! type := '' | '?' | 'x?' | 'X?' | identifier
300 //! count := parameter | integer
301 //! parameter := argument '$'
303 //! In the above grammar, `text` may not contain any `'{'` or `'}'` characters.
305 //! # Formatting traits
307 //! When requesting that an argument be formatted with a particular type, you
308 //! are actually requesting that an argument ascribes to a particular trait.
309 //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as
310 //! well as [`isize`]). The current mapping of types to traits is:
312 //! * *nothing* ⇒ [`Display`]
313 //! * `?` ⇒ [`Debug`]
314 //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers
315 //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers
316 //! * `o` ⇒ [`Octal`]
317 //! * `x` ⇒ [`LowerHex`]
318 //! * `X` ⇒ [`UpperHex`]
319 //! * `p` ⇒ [`Pointer`]
320 //! * `b` ⇒ [`Binary`]
321 //! * `e` ⇒ [`LowerExp`]
322 //! * `E` ⇒ [`UpperExp`]
324 //! What this means is that any type of argument which implements the
325 //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations
326 //! are provided for these traits for a number of primitive types by the
327 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
328 //! then the format trait used is the [`Display`] trait.
330 //! When implementing a format trait for your own type, you will have to
331 //! implement a method of the signature:
334 //! # #![allow(dead_code)]
336 //! # struct Foo; // our custom type
337 //! # impl fmt::Display for Foo {
338 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
339 //! # write!(f, "testing, testing")
343 //! Your type will be passed as `self` by-reference, and then the function
344 //! should emit output into the `f.buf` stream. It is up to each format trait
345 //! implementation to correctly adhere to the requested formatting parameters.
346 //! The values of these parameters will be listed in the fields of the
347 //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also
348 //! provides some helper methods.
350 //! Additionally, the return value of this function is [`fmt::Result`] which is a
351 //! type alias of [`Result`]`<(), `[`std::fmt::Error`]`>`. Formatting implementations
352 //! should ensure that they propagate errors from the [`Formatter`] (e.g., when
353 //! calling [`write!`]). However, they should never return errors spuriously. That
354 //! is, a formatting implementation must and may only return an error if the
355 //! passed-in [`Formatter`] returns an error. This is because, contrary to what
356 //! the function signature might suggest, string formatting is an infallible
357 //! operation. This function only returns a result because writing to the
358 //! underlying stream might fail and it must provide a way to propagate the fact
359 //! that an error has occurred back up the stack.
361 //! An example of implementing the formatting traits would look
368 //! struct Vector2D {
373 //! impl fmt::Display for Vector2D {
374 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
375 //! // The `f` value implements the `Write` trait, which is what the
376 //! // write! macro is expecting. Note that this formatting ignores the
377 //! // various flags provided to format strings.
378 //! write!(f, "({}, {})", self.x, self.y)
382 //! // Different traits allow different forms of output of a type. The meaning
383 //! // of this format is to print the magnitude of a vector.
384 //! impl fmt::Binary for Vector2D {
385 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
386 //! let magnitude = (self.x * self.x + self.y * self.y) as f64;
387 //! let magnitude = magnitude.sqrt();
389 //! // Respect the formatting flags by using the helper method
390 //! // `pad_integral` on the Formatter object. See the method
391 //! // documentation for details, and the function `pad` can be used
392 //! // to pad strings.
393 //! let decimals = f.precision().unwrap_or(3);
394 //! let string = format!("{:.*}", decimals, magnitude);
395 //! f.pad_integral(true, "", &string)
400 //! let myvector = Vector2D { x: 3, y: 4 };
402 //! println!("{}", myvector); // => "(3, 4)"
403 //! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
404 //! println!("{:10.3b}", myvector); // => " 5.000"
408 //! ### `fmt::Display` vs `fmt::Debug`
410 //! These two formatting traits have distinct purposes:
412 //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully
413 //! represented as a UTF-8 string at all times. It is **not** expected that
414 //! all types implement the [`Display`] trait.
415 //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types.
416 //! Output will typically represent the internal state as faithfully as possible.
417 //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In
418 //! most cases, using `#[derive(Debug)]` is sufficient and recommended.
420 //! Some examples of the output from both traits:
423 //! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
424 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
425 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
430 //! There are a number of related macros in the [`format!`] family. The ones that
431 //! are currently implemented are:
433 //! ```ignore (only-for-syntax-highlight)
434 //! format! // described above
435 //! write! // first argument is a &mut io::Write, the destination
436 //! writeln! // same as write but appends a newline
437 //! print! // the format string is printed to the standard output
438 //! println! // same as print but appends a newline
439 //! eprint! // the format string is printed to the standard error
440 //! eprintln! // same as eprint but appends a newline
441 //! format_args! // described below.
446 //! This and [`writeln!`] are two macros which are used to emit the format string
447 //! to a specified stream. This is used to prevent intermediate allocations of
448 //! format strings and instead directly write the output. Under the hood, this
449 //! function is actually invoking the [`write_fmt`] function defined on the
450 //! [`std::io::Write`] trait. Example usage is:
453 //! # #![allow(unused_must_use)]
454 //! use std::io::Write;
455 //! let mut w = Vec::new();
456 //! write!(&mut w, "Hello {}!", "world");
461 //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`]
462 //! macro, the goal of these macros is to avoid intermediate allocations when
463 //! printing output. Example usage is:
466 //! print!("Hello {}!", "world");
467 //! println!("I have a newline {}", "character at the end");
471 //! The [`eprint!`] and [`eprintln!`] macros are identical to
472 //! [`print!`] and [`println!`], respectively, except they emit their
473 //! output to stderr.
475 //! ### `format_args!`
477 //! This is a curious macro used to safely pass around
478 //! an opaque object describing the format string. This object
479 //! does not require any heap allocations to create, and it only
480 //! references information on the stack. Under the hood, all of
481 //! the related macros are implemented in terms of this. First
482 //! off, some example usage is:
485 //! # #![allow(unused_must_use)]
487 //! use std::io::{self, Write};
489 //! let mut some_writer = io::stdout();
490 //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
492 //! fn my_fmt_fn(args: fmt::Arguments) {
493 //! write!(&mut io::stdout(), "{}", args);
495 //! my_fmt_fn(format_args!(", or a {} too", "function"));
498 //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`].
499 //! This structure can then be passed to the [`write`] and [`format`] functions
500 //! inside this module in order to process the format string.
501 //! The goal of this macro is to even further prevent intermediate allocations
502 //! when dealing with formatting strings.
504 //! For example, a logging library could use the standard formatting syntax, but
505 //! it would internally pass around this structure until it has been determined
506 //! where output should go to.
508 //! [`fmt::Result`]: Result
509 //! [`Result`]: core::result::Result
510 //! [`std::fmt::Error`]: Error
511 //! [`write!`]: core::write
512 //! [`write`]: core::write
513 //! [`format!`]: crate::format
514 //! [`to_string`]: crate::string::ToString
515 //! [`writeln!`]: core::writeln
516 //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt
517 //! [`std::io::Write`]: ../../std/io/trait.Write.html
518 //! [`print!`]: ../../std/macro.print.html
519 //! [`println!`]: ../../std/macro.println.html
520 //! [`eprint!`]: ../../std/macro.eprint.html
521 //! [`eprintln!`]: ../../std/macro.eprintln.html
522 //! [`format_args!`]: core::format_args
523 //! [`fmt::Arguments`]: Arguments
524 //! [`format`]: crate::format
526 #![stable(feature = "rust1", since = "1.0.0")]
528 #[unstable(feature = "fmt_internals", issue = "none")]
529 pub use core::fmt::rt;
530 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
531 pub use core::fmt::Alignment;
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub use core::fmt::Error;
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub use core::fmt::{write, ArgumentV1, Arguments};
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub use core::fmt::{Binary, Octal};
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub use core::fmt::{Debug, Display};
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub use core::fmt::{Formatter, Result, Write};
544 #[stable(feature = "rust1", since = "1.0.0")]
545 pub use core::fmt::{LowerExp, UpperExp};
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub use core::fmt::{LowerHex, Pointer, UpperHex};
549 #[cfg(not(no_global_oom_handling))]
552 /// The `format` function takes an [`Arguments`] struct and returns the resulting
553 /// formatted string.
555 /// The [`Arguments`] instance can be created with the [`format_args!`] macro.
564 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
565 /// assert_eq!(s, "Hello, world!");
568 /// Please note that using [`format!`] might be preferable.
572 /// let s = format!("Hello, {}!", "world");
573 /// assert_eq!(s, "Hello, world!");
576 /// [`format_args!`]: core::format_args
577 /// [`format!`]: crate::format
578 #[cfg(not(no_global_oom_handling))]
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn format(args: Arguments<'_>) -> string::String {
581 let capacity = args.estimated_capacity();
582 let mut output = string::String::with_capacity(capacity);
583 output.write_fmt(args).expect("a formatting trait implementation returned an error");