"statics cannot evaluate destructors" in Rust

Viewed 267

I'm getting the follow compile error:

static optionsRegex: regex::Regex
    = match regex::Regex::new(r###"$(~?[\w-]+(?:=[^,]*)?(?:,~?[\w-]+(?:=[^,]*)?)*)$"###) {
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ statics cannot evaluate destructors
        Ok(r) => r,
        Default => panic!("Invalid optionsRegex")
};

More details: I need to access a compiled regexp to be used by struct when creating. Any Rust documentation links or explanation appreciated.

P.S. I think I understand that Rust needs to know when to destruct it but I have no idea how to make it other than just avoid making it static and pass some struct with all the regexps every time it's needed when creating the struct.

1 Answers

Lazily initializing and safely re-using a static variable such as a regular expression is one of the primary use-cases of the once_cell crate. Here's an example of a validation regex that is only compiled once and re-used in a struct constructor function:

use once_cell::sync::OnceCell;
use regex::Regex;

struct Struct;

impl Struct {
    fn new(options: &str) -> Result<Self, &str> {
        static OPTIONS_REGEX: OnceCell<Regex> = OnceCell::new();
        let options_regex = OPTIONS_REGEX.get_or_init(|| {
            Regex::new(r###"$(~?[\w-]+(?:=[^,]*)?(?:,~?[\w-]+(?:=[^,]*)?)*)$"###).unwrap()
        });
        if options_regex.is_match(options) {
            Ok(Struct)
        } else {
            Err("invalid options")
        }
    }
}

playground

Related