error[E0434]: can't capture dynamic environment in a fn item
--> src/main.rs:9:46
|
9 | static ref REGEX: Regex = Regex::new(search).unwrap();
| ^^^^^^
|
= help: use the `|| { ... }` closure form instead
For more information about this error, try `rustc --explain E0434`.
The error is hinting to use a closure, but I can't make it work.
In that example they are not using the text parameter of the function in the initialiser of the lazy static. In your example you are using search in the initialiser. That isn't generally allowed for statics and it isn't clear why you want that, since it would make two consecutive calls to check() use the same regex, defeating the purpose of taking it as a function parameter in the first place.
I.e. The Regex matches anything that matches "..." (a &'static str known at compile time), not a dynamic regex pattern search (known only at runtime) as in your case. You can obviously create an instance of Regex at runtime, but without the lazy_static wrapper around it, as it is in fact dynamic and not static.
lazy_static! is meant for values that are known at compile time, but where there needs to be some runtime evaluation to get the final form. In the docs, they're using lazy_static! to make a hard-coded string into a Regex on first call to the function - which is different to your case, where you want a unique Regex per value of search.
The easiest route is to stop taking a str, and ask the caller to supply a Regex instead:
If you absolutely need to take a string as search instead of a precompiled Regexand you can't afford the cost of compiling the string into a Regex on every call, then you're looking at building a cached memoization system, which can look up the right Regex each time you call it, and compile it if needed. This is not a small undertaking, and if it's something you need, then you'd be best served by searching crates.io for a caching crate that suits your needs already.