Clarify format! implicit positional references
It was a little ambiguous before how explicitl positional parameters and implicit positional parameters intermingled, and this clarifies how the two intermingle. This also updates a little bit of documentation/code examples elsewhere as well.
This commit is contained in:
parent
8174618a05
commit
23cb72b459
|
@ -56,6 +56,21 @@ example, the format string `{} {} {}` would take three parameters, and they
|
|||
would be formatted in the same order as they're given. The format string
|
||||
`{2} {1} {0}`, however, would format arguments in reverse order.
|
||||
|
||||
Things can get a little tricky once you start intermingling the two types of
|
||||
positional specifiers. The "next argument" specifier can be thought of as an
|
||||
iterator over the argument. Each time a "next argument" specifier is seen, the
|
||||
iterator advances. This leads to behavior like this:
|
||||
|
||||
```rust
|
||||
format!("{1} {} {0} {}", 1, 2) // => ~"2 1 1 2"
|
||||
```
|
||||
|
||||
The internal iterator over the argument has not been advanced by the time the
|
||||
first `{}` is seen, so it prints the first argument. Then upon reaching the
|
||||
second `{}`, the iterator has advanced forward to the second argument.
|
||||
Essentially, parameters which explicitly name their argument do not affect
|
||||
parameters which do not name an argument in terms of positional specifiers.
|
||||
|
||||
A format string is required to use all of its arguments, otherwise it is a
|
||||
compile-time error. You may refer to the same argument more than once in the
|
||||
format string, although it must always be referred to with the same type.
|
||||
|
@ -71,6 +86,14 @@ argument list and have the syntax:
|
|||
identifier '=' expression
|
||||
```
|
||||
|
||||
For example, the following `format!` expressions all use named argument:
|
||||
|
||||
```rust
|
||||
format!("{argument}", argument = "test") // => ~"test"
|
||||
format!("{name} {}", 1, name = 2) // => ~"2 1"
|
||||
format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3) // => ~"a 3 ()"
|
||||
```
|
||||
|
||||
It is illegal to put positional parameters (those without names) after arguments
|
||||
which have names. Like positional parameters, it is illegal to provided named
|
||||
parameters that are unused by the format string.
|
||||
|
|
Loading…
Reference in New Issue