Inline Format Args Capture Local Variables

Rust 2021 placeholders capture identifiers directly, so format!, println!, and panic! read like the text they print while width and precision specs still apply.

RustCli Tooling

Code

rustsnippet
20 lines
fn main() {
    let user = "ada";
    let score = 9;
    let ratio = 0.4257;

    // Rust 2021 起占位符直接捕获局部变量:{user} 等价于显式传参的旧写法
    println!("user={user} score={score}");

    // 显式写法仍然可用,两种可以混在同一行
    println!("user={} score={score}", user);

    // 内联占位符同样支持格式规格:宽度、对齐、精度
    println!("padded: |{score:>4}|");
    println!("ratio: {ratio:.2} ({:.0}%)", ratio * 100.0);

    // Debug 用 {x:?},美化多行用 {x:#?}
    let tags = vec!["go", "rust"];
    println!("debug: {tags:?}");
    println!("pretty: {tags:#?}");
}

How the file behaves

Structurally, expect the function main and nothing else.

What to watch for

  • The package manager never enters the picture for this snippet.

Using it

Entry signature: fn main()

Look for the user=, padded: |, ratio: prefixes as the program runs; the tags pair every line with its step.

Key statements

let tags = vec!["go", "rust"];
let ratio = 0.4257;
let user = "ada";

Interactive Tools for This Topic

FAQ

What does Inline Format Args Capture Local Variables print when run?
Invoke the file as-is — the `user=`, `padded: |`, `ratio:` prefixes identify which step printed each line.