]> git.lizzy.rs Git - rust.git/blob - src/doc/unstable-book/src/library-features/format-args-capture.md
Rollup merge of #73918 - GuillaumeGomez:cleanup-e0715, r=Dylan-DPC
[rust.git] / src / doc / unstable-book / src / library-features / format-args-capture.md
1 # `format_args_capture`
2
3 The tracking issue for this feature is: [#67984]
4
5 [#67984]: https://github.com/rust-lang/rust/issues/67984
6
7 ------------------------
8
9 Enables `format_args!` (and macros which use `format_args!` in their implementation, such
10 as `format!`, `print!` and `panic!`) to capture variables from the surrounding scope.
11 This avoids the need to pass named parameters when the binding in question
12 already exists in scope.
13
14 ```rust
15 #![feature(format_args_capture)]
16
17 let (person, species, name) = ("Charlie Brown", "dog", "Snoopy");
18
19 // captures named argument `person`
20 print!("Hello {person}");
21
22 // captures named arguments `species` and `name`
23 format!("The {species}'s name is {name}.");
24 ```
25
26 This also works for formatting parameters such as width and precision:
27
28 ```rust
29 #![feature(format_args_capture)]
30
31 let precision = 2;
32 let s = format!("{:.precision$}", 1.324223);
33
34 assert_eq!(&s, "1.32");
35 ```
36
37 A non-exhaustive list of macros which benefit from this functionality include:
38 - `format!`
39 - `print!` and `println!`
40 - `eprint!` and `eprintln!`
41 - `write!` and `writeln!`
42 - `panic!`
43 - `unreachable!`
44 - `unimplemented!`
45 - `todo!`
46 - `assert!` and similar
47 - macros in many thirdparty crates, such as `log`