0
0
Rustprogramming~5 mins

Formatting output in Rust

Choose your learning style9 modes available
Introduction

Formatting output helps you show information clearly and nicely on the screen. It makes numbers, text, and other data easier to read.

When you want to show a number with a fixed number of decimal places.
When you want to add spaces or align text in columns.
When you want to include variables inside a message.
When you want to display data in a specific style, like hexadecimal or binary.
Syntax
Rust
println!("format string", values...);

// Example:
println!("Hello, {}!", name);

The {} inside the string is a placeholder for values.

You can add formatting inside the braces, like {:.2} to show 2 decimal places.

Examples
Prints a greeting with the name inserted.
Rust
let name = "Alice";
println!("Hello, {}!", name);
Shows the number pi rounded to 2 decimal places.
Rust
let pi = 3.14159;
println!("Pi rounded: {:.2}", pi);
Prints the number in hexadecimal format with 0x prefix.
Rust
let number = 255;
println!("Number in hex: {:#x}", number);
Prints the word 'Rust' right-aligned in a 10-character wide space.
Rust
println!("{:>10}", "Rust");
Sample Program

This program shows how to format different types of output: inserting a name, rounding a number, showing a hex value, and aligning text.

Rust
fn main() {
    let name = "Bob";
    let score = 93.4567;
    let hex_value = 48879;

    println!("Player: {}", name);
    println!("Score: {:.1}", score);
    println!("Hex value: {:#x}", hex_value);
    println!("{:>8}", "End");
}
OutputSuccess
Important Notes

You can use {{ and }} to print curly braces literally.

Formatting works with many types like numbers, strings, and more.

Summary

Use {} as placeholders to insert values in strings.

You can control number of decimals, alignment, and number base.

Formatting makes output easier to read and understand.