I'm writing some code that writes content to files that are rotated hourly. My current approach has a struct that holds an Option<std::io::BufWriter<std::fs::File>>
and a number representing the current hour.
I wish to make the current_file
optional so that it doesn't create an empty file when the struct is created, in case there is no content written to it later.
I've come up with this code on the Playground: Rust Playground
This compiles and appears to run fine, I'm just looking to see if there are any other/better approaches to this kind of thing?
Note that the code in the Playground is altered from the real code - in the real code, the content is passed to write_some_content
and the hour comes from a DateTime<Local>
from chrono
. In the real code, the path to the file is worked out based on the date/time and a base path string, creating files like /tmp/2020/08/07/10.txt
- this is done in a separate function, but I wanted to keep the playground simple.
In the real code, the FileWriter
is only used on a single thread, so I'm not worried about any threading issues - the FileWriter
completely owns the BufWriter
.