🎓 A1Learner
🔍

Rust Output

Output is the text a Rust program prints. The println! macro prints a line of text.

println! prints a whole line

println! prints its text and moves to a new line:

println!("Hello, Rust!");

print! stays on the same line

print! leaves off the new line, so the next print carries on where it stopped:

print!("one ");
print!("two");
println!(" three");

Slots hold a place for a value

Each {} in the text is a slot. The values after the text fill the slots in order:

let name = "Ana";
println!("{} has {} points", name, 9);

format! builds text instead of printing

format! works like println! but hands the finished text back as a String, for you to print, save or check later:

let msg = format!("{} + {} = {}", 2, 3, 5);
println!("{}", msg);

Build a report, then print it once

format! builds text from pieces and hands it back as a String. One call can build the whole report. You can print, save or test that String:

let report = format!("{:<8}{:>5}\n{:<8}{:>5}\n{:<8}{:>5}", "item", "qty", "pens", 12, "pads", 3);
print!("{report}");

Write without the macros

println! is a friendly helper over a lower-level tool: the Write trait. The standard output is one of its targets. So you can send bytes yourself. And flush pushes them out at once:

use std::io::{self, Write};
io::stdout().write_all("one moment".as_bytes()).unwrap();
io::stdout().flush().unwrap();
println!(" - ready");

Example

fn main() {
    let pi = 3.14159;
    println!("pi to 2dp = {:.2}", pi);
    print!("loading");
    println!("... done");
    println!("padded = {:04}", 7);
    let msg = format!("pi is about {}", 3);
    println!("{}", msg);
}

Key points

  • Use eprintln! to print an error message to the error output, not the normal output
  • {:?} : a slot that shows the value in a detailed way, useful while fixing bugs
  • {:.2} : a slot for a number, shown with 2 digits after the point
  • Inline slots: write {name} in the text to print the variable called name, with no extra argument after the string
  • Redirecting splits the two outputs: saving normal output to a file with > output.txt captures println! lines, while eprintln! errors stay on screen — that split is why tools print results and errors to different streams
  • Rust checks every slot against the arguments while compiling.
  • A missing argument is a compile error.
  • It is not a blank at run time

In this example, {:.2} prints pi rounded to two digits, so 3.14159 becomes 3.14. Next, print! prints "loading" and stays on the same line. The println! after it adds "... done" on that same line, then moves down. {:04} prints the number 7 padded with zeros to width 4, giving 0007. Finally, format! builds the text "pi is about 3" and saves it in msg, and the last println! prints it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Which slot prints a value in the detailed, programmer-friendly way?