"I'm new to Rust and I'm working on a project where I need to scan files within a large number of folders and save the filtered data to a JSON file. I'm currently using Rayon to perform a quick foreach loop on a 'Vec' containing the folders. Within the loop, I read a file, filter the useful information and save it to a file.
This is the final working version. However I suspect is not the best solution.
fn main() {
// ...
// Imagine this is full of data
let mut folder_nas: Vec<FolderNAS> = Vec::new();
// Open a out.json file to store the results in append mode
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(FILENAME)
.unwrap();
file.write_all("Some data").unwrap();
folder_nas.par_iter().for_each(|x| {
let mut file_iterator = OpenOptions::new()
.write(true)
.append(true)
.open(FILENAME)
.unwrap();
file_iterator
.write_all("Some filtered data")
.unwrap();
});
file.write_all("Some data").unwrap();
}
At first, coming from other languages I tried this.
fn main() {
// ...
// Imagine this is full of data
let mut folder_nas: Vec<FolderNAS> = Vec::new();
// Open a out.json file to store the results in append mode
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(FILENAME)
.unwrap();
file.write_all("Some data").unwrap();
folder_nas.par_iter().for_each(|x| {
// Notice the name difference
file.write_all("Some filtered data")
.unwrap();
});
file.write_all("Some data").unwrap();
}
This approach ended up giving me an error as the file
variable is used in the for_each
and later. My solution is opening a new OpenOptions
writer in the for_each
. But my question is, how could I use the file
variable and don't create a new writer?