Output multiple variables using println!() in Rust

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson we take a look at how println!() can be used to output multiple variables using formatter placeholders.

Instructor: [00:00] To output multiple variables, println supports multiple placeholders as well. If we have variable name and another name, we can use println, placeholder, some string and another placeholder, and then pass it the first variable and then the second variable.

[00:21] When this code runs, Rust will replace the first variable with the first placeholder and the second variable with the second placeholder. This can be done with as many placeholders as we need.

[00:35] We save the file and run the program using cargo run. We will see that it will output has kind of end of this.

J. Matthew
J. Matthew
~ 4 years ago

This example only compounds my question from the previous video where only one variable was involved. Why add the variables separately from where they will be used in the string? Why doesn't Rust do something like println!("{name} and {another_name}"); instead?

Pascal Precht
Pascal Prechtinstructor
~ 4 years ago

Please see my comment in the other lesson: https://egghead.io/lessons/rust-variables-and-mutability-in-rust

Also, I know it's not exactly the same, but you can do named interpolation as well (at least in format!()):

format!("{argument}", argument = "test");
Markdown supported.
Become a member to join the discussionEnroll Today