我有许多重复的常量,其形式为:
pub const FOO_REGEX: Regex = Regex::new(r"foo.*").unwrap();
pub const BAR_REGEX: Regex = Regex::new(r"bar.*").unwrap();
我想通过使用 macro_rules!
宏来简单地实现这一点。
我尝试过:
macro_rules! pattern {
($value:literal) => {
Regex::new($value).unwrap()
}
}
pub const FOO_REGEX: Regex = pattern!(r"foo.*");
但是编译器提示:
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> lib.rs:7:9
|
7 | Regex::new($value).unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
11 | pub const FOO_REGEX: Regex = pattern!(r"foo.*");
| ------------------ in this macro invocation
每this guide我尝试了许多可用的指示符选项,例如 expr
、ident
,但我仍然无法编译宏。
为什么literal
指示符不适用于此宏表达式?
最佳答案
这与宏无关:如果直接编写代码( playground ),您会得到相同的错误。这里的问题是,调用 Regex::new
不是文字 (1),并且无法在编译时求值 ( yet? )。您将需要使用类似 lazy_static
的内容crate 以确保在运行时调用 Regex::new
来编译正则表达式:
use regex::Regex;
use lazy_static::lazy_static;
lazy_static!{
pub static ref FOO_REGEX: Regex = Regex::new(r"foo.*").unwrap();
}
(1) 引用自 this answer :
A literal is a value written as-is in the code:
true
,1
,"hello"
; the result of an expression [likeRegex::new
] cannot be a literal (by definition). The resulting types may look similar (or even be identical) but types are irrelevant here.
关于rust - 为什么 `Regex::new`的结果不能赋值给常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170011/