Skip to content

Capture a Report with Write

The Course
•
25 min study

The previous lesson freed the input loop from the console. Output has the same problem. A function that calls println! always writes to the terminal, so a test can only check it by a person reading the screen. The fix mirrors the input side: accept the destination as a parameter, bounded by a trait, and let the caller choose.

std::io::Write describes anything that accepts bytes: stdout, a file, a network socket, or a plain Vec<u8> in memory. writeln!(output, ...) works like println! but sends its line to output, and, unlike println!, it returns an io::Result<()> so a failure reaches your code instead of crashing the program. Propagate it with ? when more work follows, or return it directly when it is the last thing the function does.

For a test, pass &mut bytes where bytes is a Vec<u8>. A mutable reference to a writer is itself a writer, so the function fills your vector, and you still own it afterward. String::from_utf8(bytes) then turns the captured bytes back into text you can compare.

Predict and run

Which destination does report write to? When does any text reach the console?

Predict, then run Rust
use std::io::{self, Write};

fn report(mut output: impl Write, count: usize) -> io::Result<()> {
    writeln!(output, "Pending: {count}")
}

fn main() -> io::Result<()> {
    let mut bytes = Vec::new();
    report(&mut bytes, 2)?;
    let text = String::from_utf8(bytes).expect("report writes UTF-8");
    print!("Captured: {text}");
    Ok(())
}
Check your prediction
Text
Captured: Pending: 2

report wrote into the vector, not the console. Nothing appears until main prints the captured text, and the Captured: prefix proves that this line came through the vector. print! rather than println! is used because the text already ends with the newline writeln! added. Now replace the call with report(io::stdout().lock(), 2)?; and remove the capture and print lines. Predict the output, and notice that report itself did not change at all.

Lend the buffer, do not give it away

The &mut in report(&mut bytes, 2) is not decoration. impl Write would also accept the vector itself, but then report takes ownership of it, and the captured bytes disappear when report returns:

Rust
fn main() -> io::Result<()> {
    let bytes = Vec::new();
    report(bytes, 2)?;
    let text = String::from_utf8(bytes).expect("report writes UTF-8");
    print!("Captured: {text}");
    Ok(())
}

This fails with error[E0382]: use of moved value: bytes. Lending the vector with &mut lets report write into it while main keeps ownership, which is the beginner-course borrowing rule doing useful work.

Writes can fail

Because writeln! returns a Result, a test can also check how your code behaves when the destination fails, for example when the reader of a pipe has gone away. You only need a type whose write always returns an error.

Report into a writer that refuses Rust
use std::io::{self, Write};

struct ClosedPipe;

impl Write for ClosedPipe {
    fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
        Err(io::Error::new(io::ErrorKind::BrokenPipe, "reader went away"))
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn report(mut output: impl Write, pending: usize, finished: usize) -> io::Result<()> {
    writeln!(output, "Pending: {pending}")?;
    writeln!(output, "Finished: {finished}")
}

fn main() {
    let mut bytes = Vec::new();
    println!("Vec: {:?}", report(&mut bytes, 1, 2).map(|_| bytes.len()));
    match report(ClosedPipe, 1, 2) {
        Ok(()) => println!("Closed pipe: written"),
        Err(error) => println!("Closed pipe: {:?}", error.kind()),
    }
}
Text
Vec: Ok(23)
Closed pipe: BrokenPipe

The vector received both lines, 23 bytes including their newlines. With ClosedPipe, the first writeln! failed and ? returned at once, so the second line was never attempted. The Day 7 checks use a writer just like this one to prove the queue passes write errors up to main.

Never drop a write result

If you write writeln!(output, ...); without ?, the program compiles, but the compiler warns unused Result that must be used. The error has been thrown away. Treat that warning as a bug: add ?, or return the result.

Practice

Exercise

Your turn

Write receipt(output: impl Write) -> io::Result<()> that sends two lines to the writer: ID: 7 and Status: pending. Capture its output in a vector and assert that the text is exactly "ID: 7\nStatus: pending\n", including the final newline. Then print Receipt checked.

Your working space Rust
use std::io::{self, Write};

fn receipt(mut output: impl Write) -> io::Result<()> {
    // Write ID: 7 and Status: pending on separate lines.
    Ok(())
}

fn main() -> io::Result<()> {
    let mut bytes = Vec::new();
    receipt(&mut bytes)?;
    // Compare the bytes or convert them to text first.
    Ok(())
}
Hint 1: the idea

Use the supplied writer in both macro calls. The first write can fail before the second begins, so it needs ?.

Hint 2: a first step

Start with writeln!(output, "ID: 7")?; and let the second writeln! be the function's final expression.

Worked solution
Run the solution Rust
use std::io::{self, Write};

fn receipt(mut output: impl Write) -> io::Result<()> {
    writeln!(output, "ID: 7")?;
    writeln!(output, "Status: pending")
}

fn main() -> io::Result<()> {
    let mut bytes = Vec::new();
    receipt(&mut bytes)?;
    let text = String::from_utf8(bytes).expect("receipt writes UTF-8");
    assert_eq!(text, "ID: 7\nStatus: pending\n");
    println!("Receipt checked");
    Ok(())
}
Text
Receipt checked

The assertion compares the whole transcript, separators included, so a missing final newline or a swapped line order would fail it. The second writeln! has no semicolon: its io::Result<()> is the function's return value. The next lesson puts reading and writing together and replays a whole session from a fixture.

Was this article helpful?

Your response is saved on this device.