|
19 | 19 | //! format!("The number is {}", 1); // => "The number is 1" |
20 | 20 | //! format!("{:?}", (3, 4)); // => "(3, 4)" |
21 | 21 | //! format!("{value}", value=4); // => "4" |
| 22 | +//! let people = "Rustaceans"; |
| 23 | +//! format!("Hello {people}!"); // => "Hello Rustaceans!" |
22 | 24 | //! format!("{} {}", 1, 2); // => "1 2" |
23 | 25 | //! format!("{:04}", 42); // => "0042" with leading zeros |
24 | 26 | //! format!("{:#?}", (100, 200)); // => "( |
|
82 | 84 | //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" |
83 | 85 | //! ``` |
84 | 86 | //! |
| 87 | +//! If a named parameter does not appear in the argument list, `format!` will |
| 88 | +//! reference a variable with that name in the current scope. |
| 89 | +//! |
| 90 | +//! ``` |
| 91 | +//! let argument = 2 + 2; |
| 92 | +//! format!("{argument}"); // => "4" |
| 93 | +//! |
| 94 | +//! fn make_string(a: u32, b: &str) -> String { |
| 95 | +//! format!("{b} {a}") |
| 96 | +//! } |
| 97 | +//! make_string(927, "label"); // => "label 927" |
| 98 | +//! ``` |
| 99 | +//! |
85 | 100 | //! It is not valid to put positional parameters (those without names) after |
86 | 101 | //! arguments that have names. Like with positional parameters, it is not |
87 | 102 | //! valid to provide named parameters that are unused by the format string. |
|
100 | 115 | //! println!("Hello {:1$}!", "x", 5); |
101 | 116 | //! println!("Hello {1:0$}!", 5, "x"); |
102 | 117 | //! println!("Hello {:width$}!", "x", width = 5); |
| 118 | +//! let width = 5; |
| 119 | +//! println!("Hello {:width$}!", "x"); |
103 | 120 | //! ``` |
104 | 121 | //! |
105 | 122 | //! This is a parameter for the "minimum width" that the format should take up. |
@@ -574,6 +591,7 @@ use crate::string; |
574 | 591 | /// [`format_args!`]: core::format_args |
575 | 592 | /// [`format!`]: crate::format |
576 | 593 | #[cfg(not(no_global_oom_handling))] |
| 594 | +#[must_use] |
577 | 595 | #[stable(feature = "rust1", since = "1.0.0")] |
578 | 596 | pub fn format(args: Arguments<'_>) -> string::String { |
579 | 597 | let capacity = args.estimated_capacity(); |
|
0 commit comments