Created
March 7, 2023 19:59
-
-
Save dcormier/837e67d5193fb762e6ca5ef49a9aad9b to your computer and use it in GitHub Desktop.
A macro (with examples) to simplify Rust `once_cell` usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There was a discussion (matklad/once_cell#189) about including something like this in
once_cell
, but they decided not to.