Formatting output

Rust has built-in formatting capabilities that can be used to print data. I'm starting with this chapter because many of our early examples will require some sort of output to demonstrate correct behavior.

We'll use the pre-constructed Hello World main.rs as our baseline:

fn main() {
    println!("Hello, world!");
}

Please notice the "play" button in the above sample to see what the code does in real-time.

As you expected this code prints Hello, world! to the standard output with a new-line at the end. Strings can include the {} placeholder, which will be replaced by the arguments that follow the string.

fn main() {
    println!("Hello, {} world!", "Rust");
}

Rust figures out the "right" format for most data-types through the Display trait. (I'll cover later what traits are, don't worry about it for now)

So this works just fine:

fn main() {
    println!("Hello, {} time!", 1);
}

Like in many other development languages, you can chain the arguments together:

fn main() {
    println!("Hello, {}. You were here {} times!", "Marcel", 2);
}

If you want to re-use an argument, or arguments are in a different order that your format, you can number the placeholders:

fn main() {
    println!("Hello, {1}. {1} was here {0} times!", 2, "Marcel");
}

(Complex) types, that do not implement the Display trait, often implement a Debug trait. Content for debug purposes can be visualized with {:?}. Like:

fn main() {
    println!("Hello, {:?}...", ("Marcel", 1));
}

The {} and {:?} formats will cover 99% of the use cases. More complex formatting use-cases are described here: String formatting

Exercise

With the information from the above-mentioned link, try to format the following number: 3.14159265359, such that it only shows the first 2 decimal places: 3.14.

Good luck!

fn main() {
    println!("π is {}!", 3.14159265359);
}

Reference material