I would like to make a struct whose constructor can only be called once. For example:
pub struct Example;
impl Example {
pub fn new() -> Self {
// Do stuff
}
}
fn main() {
Example::new() // This should work fine
Example::new() // This should panic
}
The only way I've figured out so far is to use a static mut: bool and make the constructor unsafe:
static mut CONSTRUCTED: bool = false;
pub struct Example;
impl Example {
pub unsafe fn new() {
if CONSTRUCTED {
panic!("You many only construct Example once");
}
else {
CONSTRUCTED = true;
}
}
}
While this is fine, I would like to find a solution that doesn't use unsafe rust, or at least doesn't force someone the Example struct to use unsafe rust. Maybe it could be done using the FnOnce trait?
To reiterate, my question is this: Can I make a public function in safe rust that can only be called once, and, if so, how?
new(), you would incur undefined behavior for mutating/readingCONSTRUCTED. A simple way to fix the code as provided is to replaceboolwithAtomicBool, which is safe and efficient: playground.stdout()) intoExample::new. That means it can be possible to create twoExamples that wrap different output streams. Bear in mind, anything that can write to stdout can mess up your box drawing code just as much as creating twoExamples, so it's still up to the user not to do anything else with stdout after creating anExamplefrom it, but that's the same as your original code.