如何使编译的Regexp成为全局变量

vit*_*ral 22 rust

我有几个在运行时定义的正则表达式,我想让它们成为全局变量.

为了给您一个想法,以下代码有效:

use regex::Regex; // 1.1.5

fn main() {
    let RE = Regex::new(r"hello (\w+)!").unwrap();
    let text = "hello bob!\nhello sue!\nhello world!\n";
    for cap in RE.captures_iter(text) {
        println!("your name is: {}", &cap[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我希望它是这样的:

use regex::Regex; // 1.1.5

static RE: Regex = Regex::new(r"hello (\w+)!").unwrap();

fn main() {
    let text = "hello bob!\nhello sue!\nhello world!\n";
    for cap in RE.captures_iter(text) {
        println!("your name is: {}", &cap[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
 --> src/main.rs:3:20
  |
3 | static RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
  |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

这是否意味着我需要每晚Rust以使这些变量成为全局变量,还是有其他方法可以做到这一点?

squ*_*guy 18

您可以像这样使用lazy_static宏:

use lazy_static::lazy_static; // 1.3.0
use regex::Regex; // 1.1.5

lazy_static! {
    static ref RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
}

fn main() {
    let text = "hello bob!\nhello sue!\nhello world!\n";
    for cap in RE.captures_iter(text) {
        println!("your name is: {}", &cap[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,可以省略`let re`:`static ref RE:Regex = Regex :: new(...).unwrap()`应该可以工作. (5认同)