vector - 是否可以创建一个引用惰性静态值的向量?

标签 vector static rust

编译以下代码:

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_PRIMEY_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/

相关文章:

r - 获取 R 向量中的所有最大值索引

c++ - 从文本文件读取 float 并复制到 float vector

c++ - lambda 函数对象中的静态变量如何工作?

rust - 使用 PhantomData<T> 时不满足 trait bound `T: std::default::Default`

c++ - 为什么 std::copy 抛出错误 vector 迭代器+偏移量超出范围并且无法复制

c++ - 减少STL vector 的容量

java - java中static final transient的作用是什么?

java - Java中的静态变量继承

rust - 更新注册表 `https://example.com/`

rust - 具有包含异步 block 的闭包的异步方法无法推断适当的生存期