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