Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何使已编译的Regexp成为全局变量?_Rust - Fatal编程技术网

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

Rust 如何使已编译的Regexp成为全局变量?,rust,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) { printl

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

为了给您一个想法,以下代码可以工作:

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]);
    }
}
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]);
    }
}
但是,我得到以下错误:

error[E0015]:静态中的调用仅限于常量函数、元组结构和元组变量
-->src/main.rs:3:20
|
3 | static RE:Regex=Regex::new(r“hello(\w+)!).unwrap();
|                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
这是否意味着我需要每晚生锈,以使这些变量成为全局变量,或者有其他方法可以做到这一点?

您可以这样使用宏:

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]);
    }
}
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\u static

#[macro_use]
extern crate lazy_static;

@休恩:说得对。这是因为Regex实现了Deref,对吗?@squiguy,不(Regex没有实现Deref):这是因为
lazy\u static
允许您将任何正确类型的表达式分配给
static ref
,并且
Regex::new(…)。unwrap()
具有类型
Regex
。在实际实现中,我做得更好。我创建了一个
make_regex
函数并直接分配给输出。非常方便@你能把你的解决方案也作为一个答案发布吗?它不是真正通用的。我只是简单地指出,您可以使用lazy_static使用函数(或任何其他rust构造)。这甚至可能是过时的,您现在可能能够实现true
const
类型(不确定)