0
0
Rustprogramming~5 mins

Output using println macro in Rust

Choose your learning style9 modes available
Introduction

We use the println! macro to show messages or results on the screen. It helps us see what our program is doing.

To display a greeting message to the user.
To show the result of a calculation.
To print debugging information while writing code.
To output instructions or prompts during a program.
To confirm that a program step has completed.
Syntax
Rust
println!("text to show");
println!("Hello, {}!", name);

The println! macro prints text and adds a new line at the end.

You can insert values inside the text using curly braces {} and provide the values after the comma.

Examples
Prints a simple message.
Rust
println!("Hello, world!");
Prints a message with a number inserted.
Rust
let age = 25;
println!("I am {} years old.", age);
Prints a message with a name inserted.
Rust
let name = "Alice";
println!("Welcome, {}!", name);
Sample Program

This program prints a greeting with a name, shows a score, and then prints a congratulation message.

Rust
fn main() {
    let name = "Bob";
    let score = 42;
    println!("Hello, {}!", name);
    println!("Your score is {}.", score);
    println!("Good job!");
}
OutputSuccess
Important Notes

Remember to use the exclamation mark ! after println because it is a macro, not a function.

Each println! adds a new line automatically, so you don't need to add \n inside the string unless you want extra lines.

Summary

println! is used to print text and values to the screen with a new line.

You can insert values inside the text using curly braces {}.

It helps you communicate with the user or check what your program is doing.