Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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.");
}
Output
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);
}
Output
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.");
}
Output
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);
}
Output
Pi is about 3.14
Tea     |   20
Coffee  |   35

Practice exercises

  1. Print your name and age in one sentence using two placeholders.
  2. Store a price of 49.5 in a variable and print it with exactly two decimals.
  3. Print a small table of three items and their prices, with the prices lined up on the right.