11
実行時に定義されるいくつかの正規表現があり、それらをグローバル変数にしたいと思います。コンパイルされたRegexpをグローバル変数にする方法
extern crate regex;
use regex::Regex;
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.at(1).unwrap());
}
}
しかし、私はそれがこのような何かになりたい::
は、あなたのアイデアを与えるには、次のコードは動作します
extern crate regex;
use regex::Regex;
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.at(1).unwrap());
}
}
は、しかし、私は次のエラーを取得する:
Compiling global v0.1.0 (file:///home/garrett/projects/rag/global)
src/main.rs:4:20: 4:56 error: method calls in statics are limited to constant inherent methods [E0378]
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:4:20: 4:56 help: run `rustc --explain E0378` to see a detailed explanation
src/main.rs:4:20: 4:47 error: function calls in statics are limited to struct and enum constructors [E0015]
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
^~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:4:20: 4:47 help: run `rustc --explain E0015` to see a detailed explanation
src/main.rs:4:20: 4:47 note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
src/main.rs:4 static RE: Regex = Regex::new(r"hello (\w+)!").unwrap();
これは、これらの変数をグローバルにするために夜間の錆が必要なことを意味しますか、それを行う方法は?
ありがとう!それは驚くほどうまくいった! – vitiral
ちなみに 'let re':' static ref RE:Regex = Regex :: new(...)。unwrap() 'は動作するはずです。 – huon
@huon良い点。これはRegexがDerefを正しく実装しているからです。 – squiguy