BufWriter Flush Errors Before Drop

Flush a BufWriter explicitly before it drops because Drop discards buffered data and swallows flush errors without any warning.

RustData Integrity

Code

rustsnippet
28 lines
use std::fs::{self, File};
use std::io::{BufWriter, Write};

fn save(path: &str, lines: &[&str]) -> std::io::Result<()> {
    let file = File::create(path)?;
    let mut out = BufWriter::new(file);

    for line in lines {
        writeln!(out, "{line}")?;
    }

    // Drop 会静默吞掉缓冲区残余的 flush 错误:必须在 drop 前显式 flush 并检查
    out.flush()?;
    Ok(())
}

fn main() {
    let path = std::env::temp_dir().join("bufwriter-demo.log");
    match save(path.to_str().unwrap(), &["line-1", "line-2"]) {
        Ok(()) => {
            let content = fs::read_to_string(&path).unwrap().trim().replace('
', ", ");
            println!("saved: {content}");
        }
        Err(e) => println!("save failed: {e}"),
    }
    let _ = fs::remove_file(&path);
}

What the code does

BufWriter Flush Errors Before Drop comes down to the functions save and main.

The one repetition in this snippet is the loop for line in lines. Errors ride back inside Result, forcing an explicit decision at every call site. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • Error handling is typed — each Result must be matched or forwarded with ?.

Using it

The primary signature is fn save(path: &str, lines: &[&str]) -> std::io::Result<()>

The demo output is labeled (saved:, save failed:), so every printed line maps back to its originating operation.

main is the driver: it invokes save before returning.

Key statements

match save(path.to_str().unwrap(), &["line-1", "line-2"]) {
Ok(()) => {
let content = fs::read_to_string(&path).unwrap().trim().replace('
', ", ");
println!("saved: {content}");
}
Err(e) => println!("save failed: {e}"),
}
fn save(path: &str, lines: &[&str]) -> std::io::Result<()> {
let file = File::create(path)?;
let mut out = BufWriter::new(file);
for line in lines {
writeln!(out, "{line}")?;
}
// Drop 会静默吞掉缓冲区残余的 flush 错误:必须在 drop 前显式 flush 并检查
out.flush()?;
Ok(())
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
As data, not exceptions: `Result` makes the caller handle both arms.
What does BufWriter Flush Errors Before Drop print when run?
Run it as a complete program — the output lines carry labels such as `saved:`, `save failed:`.