2016-12-27 26 views
3

下面的代码编译:是否有可能创建一个引用惰性静态值的向量?

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` 

回答

7

是。 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]; 
} 
相关问题