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?