Limiting struct instantiations

Is is possible or advisable to limit the amount of times a particular struct can be instantiated?

To be clear, I'm not talking about global mutable singletons here. I just want to be able to guarantee a struct is only instantiated once.

The struct in question is a wrapper around an application data file. Multiple threads should be able to write to the file, but only through a Mutex held by the wrapper. If multiple instances of the wrapper exist, then the mutex is worthless.

Can a struct be instantiated once?

I don't follow the argument there.

It matters not how many instances of a "wrapper", whatever that is, exist, if there is a mutex around the data then only one thread can get at it at a time.

I'm sure you will find Rust won't let you share that data around among whatever "wrappers" and threads without putting it behind an Arc.

1 Like

In cases like this, you usually have the constructor take ownership of the data file, so that the only way to make a second instance is by opening another file for it to act on.

This lets tests run concurrently on separate mock files and allows future expansion to operations that might need access to multiple sessions at the same time, like importing data from one application file to another.


If the wrapper looks like this:

struct Wrapper {
   file: Arc<Mutex<File>>

impl Wrapper {
    pub fn new () -> Self {
        let file = open("data.txt");

        Self { file: Arc::new(Mutex::new(file)) }

You could easily create multiple wrappers with each one having the same file.

@2e71828 I don't want another another instance opening the same file.

Can you prevent a file being opened more than once?

Actually I think I'm trying to solve this problem in the wrong place. And I see what you mean @2e71828.

The constructor should be provided with the File and whether or not it exists and whether or not its already open should be a problem that is tackled somewhere upstream.

It seems you are expecting some "bad actors" within your own program that might try and do that to mess things up.

It seems to me that at some top level in your program you will have the file name. That string can be given to some subsystem to open a file and then dropped. Nobody else in your code can get that file name again.

Yeah Ok.

That’s what I mean by solving the problem in the wrong place. The wrapper is exported from a library. If some higher level code is responsible for opening the file, that code can worry about who is opening files.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.