如何使编译的 Regexp 成为全局变量? [英] How to make a compiled Regexp a global variable?
本文介绍了如何使编译的 Regexp 成为全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个在运行时定义的正则表达式,我想让它们成为全局变量.
I have several regular expressions that are defined at runtime and I would like to make them global variables.
给你一个想法,以下代码有效:
To give you an idea, the following code works:
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]);
}
}
但我希望它是这样的:
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]);
}
}
但是,我收到以下错误:
However, I get the following error:
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();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
这是否意味着我需要每晚使用 Rust 才能使这些变量成为全局变量,还是有其他方法可以做到这一点?
Does this mean that I need nightly Rust in order to make these variables global, or is there another way to do it?
推荐答案
您可以使用 lazy_static 宏像这样:
You can use the lazy_static macro like this:
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]);
}
}
如果您使用的是 2015 版 Rust,您仍然可以通过以下方式使用 lazy_static
:
If you are using the 2015 edition of Rust, you can still use lazy_static
via:
#[macro_use]
extern crate lazy_static;
这篇关于如何使编译的 Regexp 成为全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文