Basic Formatting

A single placeholder is used when it is required to print a single value.

fn main() {
    println!("Number: {}", 1);
}

We can use multiple placeholders within the println!() macro. The number of placeholders should be equal to the number of values to be printed.

fn main() {
    println!("{} is a {} Community", "Join", "CloudNativeFolks");
}

If we want to convert the value to binary, hexadecimal, or octal write:

{:b},{:x},{:o}

In the placeholder for binary, hexadecimal, or octal respectively and in the value specify the number. You can use all three of them or one of them in a single expression.

fn main() {
    println!("Number : 10 \nBinary:{:b} Hexadecimal:{:x} Octal:{:o}", 10, 10, 10);
}

If we want to convert the value to binary, hexadecimal, or octal write:

{:b},{:x},{:o}

In the placeholder for binary, hexadecimal, or octal respectively and in the value specify the number. You can use all three of them or one of them in a single expression.

fn main() {
    println!("Number : 10 \nBinary:{:b} Hexadecimal:{:x} Octal:{:o}", 10, 10, 10);
}

We can perform basic math and the placeholder gets replaced with the result.

fn main() {
    println!("{} + {} = {}",10, 10, 10 + 10);
}

Placeholder for debug trait

fn main() {
    println!("{:?}", ("This is a Rustlabs", 101));
}

Knowledge check

Last updated a year ago. history