Sub topic 1
Printing with `print!` and `println!`
Prerequisites
Assume you know basic Rust syntax, functions, variables, and cargo run. You should also know that a macro is code invoked with !, and that a trait describes behavior a type can provide.
Printing text
Rust provides two common macros for writing to standard output:
print!writes text without adding a newline.println!writes text and then adds a newline.
fn main() {
print!("Loading");
println!(" complete");
println!("Next line");
}The output is:
Loading complete
Next lineBoth macros accept a format string. A format string is a string literal containing text and placeholders for values.
fn main() {
let name = "Ferris";
let count = 3;
println!("Hello, {}!", name);
println!("Items: {}", count);
}Each {} consumes one argument from left to right. Rust checks the format string and its arguments at compile time.
flowchart TD
A["println! format string"] --> B["Find placeholders"]
B --> C["Format each argument"]
C --> D["Write text and newline"]Positional, named, and inline arguments
You can select arguments by position, give them names, or capture local variables directly.
fn main() {
let name = "Ferris";
let age = 7;
println!("{} is {} years old", name, age);
println!("{0} likes {1}; {1} likes {0}", "Rust", "tea");
println!("{person} is {years} years old", person = name, years = age);
println!("{name} is {age} years old");
}Positional indexes start at zero. Named arguments make repeated or reordered values clearer. Inline capture uses a local variable whose name appears inside the braces.
Printing literal braces
To print a literal opening or closing brace, double it:
fn main() {
println!("Use {{name}} for a placeholder");
}This prints Use {name} for a placeholder. Single braces are reserved for formatting instructions.
> callout tip > Prefer named or inline arguments when a format string has several values. The names document what each value means.
Display: output meant for users
The {} placeholder uses the Display trait. Display defines a clean, user-facing representation, such as a name, number, or status message. Many standard types implement it, but a custom type must implement Display before {} can format it.
Use Display for messages users should read. Use Debug with {:?} when inspecting values during development; it is covered later.
Exercise
What does println!("{} + {} = {}", 2, 3, 2 + 3); print?
Show answer
It prints 2 + 3 = 5, followed by a newline.