Rust Output
Showing results is the first thing every program needs to do, and Rust gives you two friends for it: println! prints a line and moves to the next one, and print! prints without moving on. Most of the time you will use println!.
fn main() {
print!("Hello, ");
print!("everyone");
println!("!");
println!("This is a new line.");
}Hello, everyone! This is a new line.
Placeholders
Text in double quotes is printed as it is. To print a value, put a pair of curly brackets {} in the text, and give the value after a comma. Rust replaces each {} with the next value, in order. This is called a format string.
fn main() {
let apples = 3;
let price = 25;
println!("I bought {} apples at {} rupees each.", apples, price);
println!("That is {} rupees in total.", apples * price);
}I bought 3 apples at 25 rupees each. That is 75 rupees in total.
If the number of {} and the number of values do not match, the program does not even compile. Rust checks this for you, so a missing value can never surprise you later.
Names inside the brackets
When a value is a simple variable, you can write its name straight inside the brackets. Many people find this easier to read, because you do not have to count commas:
fn main() {
let name = "Meera";
let age = 14;
println!("{name} is {age} years old.");
}Meera is 14 years old.
Decimals and columns
Between the brackets you can also say how a value should look. {:.2} shows a number with two digits after the point, and {:5} makes a value at least five characters wide, which is handy for tables. {:<8} lines text up on the left.
fn main() {
let pi = 3.14159;
println!("Pi is about {:.2}", pi);
println!("{:<8}|{:>5}", "Tea", 20);
println!("{:<8}|{:>5}", "Coffee", 35);
}Pi is about 3.14 Tea | 20 Coffee | 35
Practice exercises
- Print your name and age in one sentence using two placeholders.
- Store a price of 49.5 in a variable and print it with exactly two decimals.
- Print a small table of three items and their prices, with the prices lined up on the right.