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();
>Solution :
Two things come into play:
- A
BufWriterabsorbes writes in memory before handing them to the operating system until either- Its buffer is full
- It has
flushcalled - It gets
Dropped
lazy_staticitems 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
BufWriterin yourmainfunction and hand a reference to it through all method calls. - A bit dirty, but you could use
dtor.