Skip to content

Commit a1217cb

Browse files
committed
Add format_args_capture to the unstable book
1 parent 8caf604 commit a1217cb

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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`

0 commit comments

Comments
 (0)