I am testing some Rust code and want to log some of the intermediate data to a file to make sure it is correct before I write the next element in the pipeline that consumes the data. In any other language I'd just write the data to a file handle stored in a static variable, but rust complains (correctly) that this is not thread safe. Since the application in question uses gstreamer this is theoretically a threat. I'll just paste my naive version below:
use std::fs::File;
use std::io::Write;
fn main() {
log_mesh("bacon");
}
static mut meshes : Option<Result<File, std::io::Error>> = None;
fn log_mesh(message: &str)
{
if let None = meshes {
meshes = Some(File::open("/tmp/meshes.txt"));
}
if let Ok(mut f) = meshes.unwrap() {
f.write_all(message.as_bytes());
f.flush();
}
}
This results in two important kinds of compile errors:
error[E0507]: cannot move out of static item
--> src/main.rs:16:24
|
16 | if let Ok(mut f) = meshes.unwrap() {
| ^^^^^^ cannot move out of static item
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src/main.rs:12:19
|
12 | if let None = meshes {
| ^^^^^^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
I have flailed around with Mutex
, lazy_static!
, mut_static
, but all of them lead me into the woods and I get lost. I assume there has to be some compact idiom to solve this problem that isn't coming up in Google search results.