Search code examples
functionrustscopecallownership

Rust: what's the distinction between calling a variable inside placeholders and outside them (as a separate argument)


(Beginner's question) After observing a few coding examples (from various sources) and syntax suggestions by Cargo Clippy, I'm still wondering whether the following blocks are just two alternatives for the same result, or actually do something different(ly) which I must be aware of.

fn main() {
    let string_1 = "Hello!";
    let string_2 = "See you!";

    println!("{} {}", string_1, string_2);
}

Or...

fn main() {
    let string_1 = "Hello!";
    let string_2 = "See you!";

    println!("{string_1} {string_2}");
}

If I use the first syntax, Cargo Clippy suggests me to use the second one instead. But, if I write println!("{} {}", &string_1, &string_2);, Clippy no longer complains, so I guess the difference between both coding blocks has to do with Rust's unique concept of "ownership".

So, am I missing something?


Solution

  • They are the same (but the second is newer, being stabilized in Rust 1.58.0, and more recommended for new code).

    The reason Clippy does not suggest the second form anymore when you take reference is because it is invalid: only identifiers (bare variable names) can be used with inline captures.