rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.92k stars 111 forks source link

Support for usage in pattern matching / if let? #209

Closed bluenote10 closed 1 year ago

bluenote10 commented 1 year ago

By reading the documentation I could not figure out how a lazy static can be used with pattern matching / if let.

lazy_static! {
    static ref SOME_OPTION: Option<Vec<i32>> = None;
}

fn foo() {
    if let Some(data) = SOME_OPTION {
        // ...
    }
}

fails to compile with

error[E0308]: mismatched types
   --> src/bookmarks.rs:195:12
    |
195 |     if let Some(data) = SOME_OPTION {}
    |            ^^^^^^^^^^   ----------- this expression has type `SOME_OPTION`
    |            |
    |            expected struct `SOME_OPTION`, found enum `Option`
    |
    = note: expected struct `SOME_OPTION`
                 found enum `std::option::Option<_>`

Is there a trick to make that work?

bluenote10 commented 1 year ago

Looks like my brain was just a little too tired. Of course this works:

if let Some(data) = &*SOME_OPTION {}

Sorry for the noise.