【问题标题】:"statics cannot evaluate destructors" in RustRust 中的“静态不能评估析构函数”
【发布时间】:2021-04-25 18:06:18
【问题描述】:

我收到以下编译错误:

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

更多细节:我需要在创建时访问一个已编译的正则表达式供 struct 使用。任何 Rust 文档链接或解释表示赞赏。

附:我想我知道 Rust 需要知道何时销毁它,但我不知道如何制作它,除了避免使其成为静态并在创建结构时每次需要它时传递一些带有所有正则表达式的结构。

【问题讨论】:

    标签: rust static destructor


    【解决方案1】:

    延迟初始化和安全地重用静态变量(例如正则表达式)是once_cell crate 的主要用例之一。这是一个验证正则表达式的示例,它只编译一次并在结构构造函数中重复使用:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2010-12-20
      • 1970-01-01
      • 2012-12-26
      • 2014-04-28
      相关资源
      最近更新 更多