The println! Macro
println! is the command you use to make your Rust program show text to you on the screen.In this page:
Basic Printing
The simplest use of println! takes a plain string literal and prints it followed by a newline. This is the very first thing most people write when learning Rust.
Example: Basic Printing
fn main() {
println!("Simple text output");
}
Login to try C/C++/Java/PHP code in the editor
Placeholders With {}
Curly braces {} act as placeholders inside the format string, filled in order by the extra arguments passed after the string. This lets you mix literal text with dynamic values in one call.
Note: Ferris is the unofficial mascot of Rust -- a friendly crab.
Example: Placeholders With {}
fn main() {
let name = "Ferris";
let age = 5;
println!("{} is {} years old", name, age);
}
Login to try C/C++/Java/PHP code in the editor
Named Arguments
You can name placeholders directly inside the braces, like {value}, and Rust matches them to named arguments passed after the format string, regardless of their position. This can make longer format strings easier to read.
Example: Named Arguments
fn main() {
let city = "Berlin";
let temp = 21;
println!("It is {} degrees in {}", temp, city);
}
Login to try C/C++/Java/PHP code in the editor
print! vs println!
print! behaves exactly like println! except it does not add a trailing newline. This means consecutive print! calls continue on the same line, which is useful for building output piece by piece.
Example: print! vs println!
fn main() {
print!("No newline here... ");
println!("but this one ends the line");
}
Login to try C/C++/Java/PHP code in the editor
- Using
println!("{}", x, y)with more placeholders or arguments than actually match, causing a compile error. - Forgetting curly braces
{}are required as placeholders and cannot be replaced with old-style%s/%dformatting. - Confusing
print!(no trailing newline) withprintln!(adds a trailing newline) and getting squished-together output.
println!prints text followed by a newline;print!prints without one.- Curly braces
{}are placeholders filled in by the arguments that follow, in order. - Named or positional arguments can be used inside the braces, like
{name}or{0}. format!builds a formattedStringwithout printing it, using the same syntax asprintln!.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: