Hello,
While going through the docs for GitHub - rust-lang/regex: An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs., I found this code snippet:
use regex::Regex;
fn some_helper_function(text: &str) -> bool {
lazy_static! {
static ref RE: Regex = Regex::new("...").unwrap();
}
RE.is_match(text)
}
What is the benefit to having the lazy_static!
inside the helper function, as opposed to the top level of the module? (I would guess that having a lazy_static!
inside the helper function's scope would make RE
unavailable to other functions in the module.)
If RE
is going to be reused in a loop inside the helper function, couldn't we skip the lazy_static!
and get an instance of a compiled regex to reuse with just a let
? Or is it that the static instance RE
will be magically preserved between different times when some_helper_function
is called? (This doesn't sit very well with me because it seems to imply a side effect that is preserved beyond the scope of the helper function.)
What is the recommended pattern for defining these lazy-initialized statics? Should the lazy_static!
be at the top level of the module versus inside the function where the values are used?
Thank you!