Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

static variable with BufWriter in Rust

I would like to get a global variable with BufWriter.

This code is executed without errors, but writing to the file is not carried out:

lazy_static! {
    static ref WRITER: Mutex<BufWriter<File>> = {
        let file = File::create("test.bin").unwrap();
        BufWriter::new(file).into()
    }
}
WRITER.lock().unwrap().write_all(&vec![1, 2, 3, 4]).unwrap();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Two things come into play:

  • A BufWriter absorbes writes in memory before handing them to the operating system until either
    • Its buffer is full
    • It has flush called
    • It gets Dropped
  • lazy_static items are never Dropped

So, to make your code work, you must do something like

let mut writer = WRITER.lock().unwrap();
writer.write_all(&vec![1, 2, 3, 4]).unwrap();
writer.flush().unwrap();

Playground (with one minor syntax error fixed)

Alternatively:

  • You construct the BufWriter in your main function and hand a reference to it through all method calls.
  • A bit dirty, but you could use dtor.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading