rust - 为什么 `Regex::new`的结果不能赋值给常量?

标签 rust

我有许多重复的常量,其形式为:

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我尝试了许多可用的指示符选项,例如 exprident,但我仍然无法编译宏。

为什么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();
}

Playground


(1) 引用自 this answer :

A literal is a value written as-is in the code: true, 1, "hello"; the result of an expression [like Regex::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/

相关文章:

rust - 通用特征实现中的生命周期

string - 在 Rust 中匹配 Option 静态字符串文字

rust - 在Amethyst ECS架构中添加事件 channel

rust - 闭包作为通用返回 `impl FnMut(T)`

rust - 我如何确定为什么已编译的 Rust 二进制文件需要特定符号?

rust - rust 中的 "const fn"可以连接字节切片吗?

error-handling - 如何使用自定义结构实现错误

rust - 人们如何在 Rust 中复制一个值?

rust - 带参数的过滤器迭代器

closures - 闭包的类型别名