Close File stored in Map in Rust

Viewed 746

I store opened files in a map: HashMap<u32, File>. Sometimes functions read_to_file and write_to_file are called. They get the file from the map and make the corresponding procedure. In order to avoid conflicts in writing and reading from the same file, I need to close the file. How can I do it?

1 Answers

According to the Rust documentation std::fs::File is:

A reference to an open file on the filesystem.

If you are storing Files in a map then they are, by definition, open. They close automatically when the variable is dropped (goes out of scope).

Instead, you may consider storing a Path in the map, and open the file on demand. If you need to store open files for some reason, then you can wrap them in an Arc<Mutex> (or an `Rc if your application is single-threaded), to prevent simultaneous access.

Related