Run code once in Rust.

Need to coordinate access to some resource in your tests? Need to run some initialization code required by multiple threads?

I’ve used the following code snippet a few times now. It blocks but it gets the job done. I’ve only used it for tests. I think I would only use it for initialization code in production.

use std::sync::{Once, ONCE_INIT};
static SYNC_OBJ: Once = ONCE_INIT;
pub fn do_some_init() {
SYNC_OBJ.call_once(|| {
let _ = some_init_fn();
Like what you read? Give Eric Opines a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.