Sub topic 3
Positional, named, and inline arguments
This chapter assumes you can write a basic Rust main function and run it with cargo run. It also assumes you know that println! takes a format string with {} placeholders. Here you will learn the three ways a placeholder can find the value it prints, how they combine, and which mistakes the compiler catches.
How a placeholder finds its value
Every {} in a format string must be matched to a value. Rust gives you three ways to do that:
- Implicit positional:
{}takes the next unused argument, counting from the left. - Explicit positional:
{0},{1}and so on take the argument at that index. - Named:
{name}takes the argument written asname = value, or, if no such argument exists, a variable callednamethat is in scope.
Implicit and explicit positions
With empty braces, arguments are used in the order you wrote them. With an index, you choose the argument yourself, and you can reuse it.
fn main() {
println!("{} + {} = {}", 2, 3, 2 + 3);
println!("{0} {1} {0}", "a", "b");
println!("{} {0} {}", "a", "b");
}This prints:
2 + 3 = 5
a b a
a a bThe third line shows a detail that surprises people. The implicit counter only advances for empty {} placeholders. It ignores {0}. So the first {} takes argument 0, the {0} takes argument 0 again, and the second {} takes argument 1. Mixing the two styles works, but it is easy to misread, so pick one style per format string unless you have a reason not to.
An argument is evaluated once, no matter how many placeholders use it:
fn next() -> i32 {
println!("called");
7
}
fn main() {
println!("{0} {0}", next());
}The output is called followed by 7 7. The function runs one time. This matters when an argument has side effects or is expensive to compute.
Named arguments
A named argument is written name = expression after the positional ones. Placeholders refer to it with {name}.
fn main() {
println!("{n} squared is {sq}", n = 5, sq = 5 * 5);
println!("{} and {x}", "first", x = "second");
}Named arguments must come after all positional arguments. Putting a positional argument after a named one is a compile error.
Named arguments are useful for two reasons. A long format string with six values is easier to check when each placeholder says what it holds. They also let you give a short name to a long expression, such as total = order.items.iter().map(|i| i.price).sum::<u32>(), and keep the format string readable.
Inline captured arguments
Since Rust 1.58, a placeholder whose name matches a variable in scope reads that variable directly. You don't need to pass it as an argument.
fn main() {
let name = "Ferris";
let age = 7;
let width = 10;
println!("{name} is {age}");
println!("[{name:>width$}]");
println!("{name} / {n}", n = age * 2);
}This prints:
Ferris is 7
[ Ferris]
Ferris / 14
</parameter>Three things are happening here:
{name}and{age}capture the local variables.- In
{name:>width$}, the part after the colon is a format specifier. The capturednameis right-aligned, and the field width comes from the captured variablewidth. Format specifiers are covered in a later chapter. For now, note that they combine freely with captured names. - The last line mixes a captured variable with an explicit named argument.
Limits of inline capture
Inline capture accepts only a plain identifier. It does not accept expressions, field access, or method calls:
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
// println!("{p.x}"); // compile error: not a valid identifier
println!("{}", p.x);
println!("{x}, {y}", x = p.x, y = p.y);
}When you need a field or an expression, pass it as a positional or named argument. Also, capture only works when the format string is a string literal. A format string stored in a variable cannot capture anything, because the compiler needs to see the names at compile time.
When names collide
If a named argument and a local variable have the same name, the explicit named argument wins:
fn main() {
let n = 1;
println!("{n} {n}", n = 2);
}This prints 2 2. The local n is ignored in that call. This is rarely what you want by accident, so avoid reusing a name that way.
Mistakes the compiler catches
Format strings are checked at compile time, so most argument mistakes never reach a running program.
| Mistake | Example | Result |
|---|---|---|
| Unused argument | `println!("{}", 1, 2)` | Compile error: argument never used |
| Too few arguments | `println!("{} {}", 1)` | Compile error: two placeholders, one argument |
| Index out of range | `println!("{2}", 1, 2)` | Compile error: invalid reference to positional argument 2 |
| Unknown name | `println!("{missing}")` | Compile error: cannot find value `missing` in this scope |
| Unused named argument | `println!("{}", 1, extra = 2)` | Compile error: named argument never used |
| Positional after named | `println!("{a} {}", a = 1, 2)` | Compile error |
The first row deserves attention. Rust rejects unused arguments, even though other languages ignore them silently. If you remove a placeholder while editing, the compiler tells you the argument is now dangling. A placeholder that refers only to {0} still counts as using argument 0, so println!("{0} {0}", x) is fine.
Choosing a style
- Use implicit
{}for short messages with one or two values, where order is obvious. - Use inline
{name}when the values are already in local variables. It is the shortest form and the easiest to read. - Use named arguments (
name = expr) when the value is an expression or a field, or when you want a descriptive label. - Use explicit indices when the same value appears more than once and you do not want to name it. This is common in messages that repeat a value, or when translating text where word order changes.
Exercise
What does this program print, and does it compile? fn main() { let a = "x"; let b = "y"; println!("{} {b} {0} {a}", a, b = "z"); }
Show answer
It compiles and prints x z x x. The first {} is implicit and takes argument 0, which is a, so it prints x. {b} refers to the named argument b = "z", which wins over the local variable b, so it prints z. {0} is argument 0 again, so it prints x. {a} has no named argument, so it captures the local variable a and prints x.
Exercise
Rewrite println!("{}: {}", p.name, p.score) so that the format string uses {name} and {score}. Why can't you write {p.name} directly?
Show answer
Write println!("{name}: {score}", name = p.name, score = p.score). Inline capture accepts only a plain identifier that names a variable in scope. p.name is a field access, which is an expression, so it must be passed as an argument with an explicit name.