Skip to content

Instantly share code, notes, and snippets.

@dcormier
Created March 7, 2023 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcormier/837e67d5193fb762e6ca5ef49a9aad9b to your computer and use it in GitHub Desktop.
Save dcormier/837e67d5193fb762e6ca5ef49a9aad9b to your computer and use it in GitHub Desktop.
A macro (with examples) to simplify Rust `once_cell` usage
macro_rules! once {
($exp:expr) => {
once!((), $exp)
};
($type:ty, $exp:expr) => {{
static ONCE: once_cell::sync::OnceCell<$type> = once_cell::sync::OnceCell::new();
ONCE.get_or_init(|| $exp)
}};
}
fn main() {
// If you run this, you can see that the expressions are executed only once.
once();
once();
once();
assert_eq!(42, calc());
assert_eq!(42, calc());
assert_eq!(42, calc());
}
fn once() {
once!(println!("Doing it only once"));
}
fn calc() -> u8 {
*once!(u8, {
println!("Calculating the value");
3 * 2 * 7 * 5 / 4 - 10
})
}
@dcormier
Copy link
Author

dcormier commented Mar 7, 2023

There was a discussion (matklad/once_cell#189) about including something like this in once_cell, but they decided not to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment