-
Notifications
You must be signed in to change notification settings - Fork 12.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
format_args_capture
to the unstable book
- Loading branch information
1 parent
8caf604
commit a1217cb
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
src/doc/unstable-book/src/library-features/format-args-capture.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# `format_args_capture` | ||
|
||
The tracking issue for this feature is: [#67984] | ||
|
||
[#67984]: https://github.com/rust-lang/rust/issues/67984 | ||
|
||
------------------------ | ||
|
||
Enables `format_args!` (and macros which use `format_args!` in their implementation, such | ||
as `format!`, `print!` and `panic!`) to capture variables from the surrounding scope. | ||
This avoids the need to pass named parameters when the binding in question | ||
already exists in scope. | ||
|
||
```rust | ||
#![feature(format_args_capture)] | ||
|
||
let (person, species, name) = ("Charlie Brown", "dog", "Snoopy"); | ||
|
||
// captures named argument `person` | ||
print!("Hello {person}"); | ||
|
||
// captures named arguments `species` and `name` | ||
format!("The {species}'s name is {name}."); | ||
``` | ||
|
||
This also works for formatting parameters such as width and precision: | ||
|
||
```rust | ||
#![feature(format_args_capture)] | ||
|
||
let precision = 2; | ||
let s = format!("{:.precision$}", 1.324223); | ||
|
||
assert_eq!(&s, "1.32"); | ||
``` | ||
|
||
A non-exhaustive list of macros which benefit from this functionality include: | ||
- `format!` | ||
- `print!` and `println!` | ||
- `eprint!` and `eprintln!` | ||
- `write!` and `writeln!` | ||
- `panic!` | ||
- `unreachable!` | ||
- `unimplemented!` | ||
- `todo!` | ||
- `assert!` and similar | ||
- macros in many thirdparty crates, such as `log` |