How to initialize std::fs:File without opening a file?

Hi there,

I am trying around with Actix and would like to store a std::fs::File in a struct, that might be used, or actually might not be used opening a file. Problem is, I need to initialize that variable with something.... but with what? As this is also in a potential multi threaded environment, i am trying to put a Mutex arround it.

struct AppState {
    data_file: Mutex<std::fs::File>
}
...
let my_var = AppState{data_file: Mutex::new(<WHAT TO PUT HERE?>)};

As the file is not always used, I would like to start with an 'empty' file var. as the file will be read quite often I do want to keep it open to not always seek a position in the file...

Any idea?

Why not Mutex<Option<File>>? None when it's unloaded, Some when it's open.

I suppose it depends on how the code should behave when the File is "empty".

3 Likes

Looks like an idea.... at least the initialization compiles, will need to put more code around it.. will let you know! Thanks!

You could also wrap the Mutex in once_cell — Rust library // Lib.rs

1 Like

The solution with the Option did the trick for me! Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.