我有几个在运行时定义的正则表达式,我想让它们成为全局变量.
为了给您一个想法,以下代码有效:
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)
| 归档时间: |
|
| 查看次数: |
1962 次 |
| 最近记录: |