Sub topic 1
Printing with print! and println!
Prerequisites
This chapter assumes you can write and run a basic Rust program with cargo run. You should know how to declare variables and define fn main. You do not need to know traits yet. Later chapters cover them when you implement your own output.
What the print macros do
Rust prints text to standard output with two macros. println! writes its text and then a newline. print! writes the text and stops, so the next output continues on the same line.
Both end in ! because they are macros, not functions. A macro runs at compile time and can accept a variable number of arguments. It can also check those arguments before your program runs.
fn main() {
print!("Loading");
print!("...");
println!(" done");
println!("Next line");
}This prints Loading... done on the first line and Next line on the second.
The first argument is a format string
The first argument must be a string literal. It is a format string, and {} inside it marks a placeholder. Each placeholder is filled by one of the arguments that follow.
fn main() {
let items = 3;
println!("You have {} items", items);
println!("{} + {} = {}", 2, 3, 2 + 3);
}A placeholder is replaced by the value converted to text. The exact conversion depends on a trait, which the Display and Debug chapters explain. For now, {} works for numbers, strings, and characters.
A bare println!() with no arguments prints only a newline. This is the usual way to add a blank line.
Buffering and print!
Standard output is usually line buffered when it is connected to a terminal. The program holds text in memory until it sees a newline. Because print! does not add a newline, a prompt written with it may not appear right away. Call flush to force it out.
use std::io::{self, Write};
fn main() {
print!("Name: ");
io::stdout().flush().unwrap();
let mut name = String::new();
io::stdin().read_line(&mut name).unwrap();
println!("Hello, {}!", name.trim());
}Without the flush call, the prompt can show up after you type your answer.
How the pieces fit
The diagram shows what happens to a call such as println!("{} items", n).
Common errors
- Passing a variable as the format string, as in
println!(text). The first argument must be a literal. Writeprintln!("{}", text)instead. - Having a different number of placeholders and arguments. This is a compile error, not a run-time one.
- Forgetting that
print!adds no newline, which leaves your next shell prompt on the same line as your output.
Exercise
A program runs print!("Enter a number: "); and then waits for input, but the prompt does not appear until after the user types. What causes this, and what is the fix?
Show answer
Standard output is line buffered, and print! does not write a newline, so the text stays in the buffer. Call std::io::stdout().flush() (with use std::io::Write;) after print! to send it immediately.
Exercise
What does this program print? fn main() { print!("a"); println!("b"); println!(); println!("{}{}", 1, 2); }
Show answer
It prints ab on the first line, an empty second line, and 12 on the third line.