编译以下代码:
let x = Regex::new(r"\d+").unwrap();
let y = Regex::new(r"asdf\d+").unwrap();
let regexes = vec![x, y];
但是这段代码不会:
lazy_static! {
static ref X_PRIME: Regex = Regex::new(r"\d+").unwrap();
static ref Y_PRIME: Regex = Regex::new(r"asdf\d+").unwrap();
}
let regexes = vec![X_PRIME, Y_PRIME];
错误是:
error[E0308]: mismatched types
--> src\syntax\lex.rs:19:33
|
19 | let regexes = vec![X_PRIME, Y_PRIME];
| ^^^^^^^ expected struct `syntax::lex::lex::X_PRIME`, found struct `syntax::lex::lex::Y_PRIME`
|
= note: expected type `syntax::lex::lex::X_PRIME`
= note: found type `syntax::lex::lex::Y_PRIME`
最佳答案
是的。 lazy_static 给出 X_PRIME
和 Y_PRIME
不同的类型,但它们都是 implement Deref<Regex>
,所以你可以这样写:
let regexes = vec![&*X_PRIME, &*Y_PRIME];
// The * dereferences the values to a `Regex` type
// The & turn them back into references `&Regex`.
你也可以只定义另一个静态:
lazy_static! {
static ref X_PRIME: Regex = Regex::new(r"\d+").unwrap();
static ref Y_PRIME: Regex = Regex::new(r"asdf\d+").unwrap();
static ref REGEXES: Vec<&'static Regex> = vec![&X_PRIME, &Y_PRIME];
}
关于vector - 是否可以创建一个引用惰性静态值的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352852/