matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.87k stars 109 forks source link

static Lazy<String> "is never used" #218

Closed Swivelgames closed 1 year ago

Swivelgames commented 1 year ago

Using once_cell::sync::Lazy and getting some funky results when I try to do Lazy<String> inside of an async main

main.rs:

mod common;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...
    let addr = SocketAddr::from(([0, 0, 0, 0], *common::PORT));

    // Variants that throw error
    let creds = common::DB_CREDENTIALS;
    // Variants that throw warning "unused_code"
    let creds = *common::DB_CREDENTIALS;
    let creds = common::DB_CREDENTIALS.as_str();
    let creds = common::DB_CREDENTIALS.to_string();
    let creds = &*common::DB_CREDENTIALS;
    let creds = &*common::DB_CREDENTIALS.as_str();
    let creds = &*common::DB_CREDENTIALS.to_string();
    let creds = String::from(&*common::DB_CREDENTIALS);

    // creds is referenced here
    let some_instance = SomeStruct::new(&creds).await;

    // ...
    // addr is referenced here
    // ...
}

common.rs:

use once_cell::sync::Lazy;

pub static PORT: Lazy<u16> = Lazy::new(|| {
    std::env::var("PORT")
        .expect("PORT environment variable must be set")
        .parse()
        .expect("PORT must be an valid port number.")
});

pub static DB_CREDENTIALS: Lazy<String> = Lazy::new(|| {
    std::env::var("DB_CREDENTIALS")
        .expect("DB_CREDENTIALS environment variable must be set")
});

The error thrown is:

cannot move out of dereference of once_cell::sync::Lazy move occurs because value has type String, which does not implement the Copy trait (rustc E0507)

Otherwise, I get the following:

static DB_CREDENTIALS is never used

[warn(dead_code)] on by default (rustc dead_code)

However, common::PORT doesn't have the same problem.

Swivelgames commented 1 year ago

Interestingly enough, if I move the Lazy<String> into main.rs, the warning goes away.

Swivelgames commented 1 year ago

Figured out the problem. With the project I'm working on, I have both a lib.rs and a main.rs. The main.rs is using the DB_CREDENTIALS, but the lib.rs isn't (as designed).

The solution was to move DB_CREDENTIALS into main.rs, since lib.rs doesn't use it :sweat_smile: