rust-lang-nursery / lazy-static.rs

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

Can I use std::env::args in lazy-static? #148

Closed pili2026 closed 5 years ago

pili2026 commented 5 years ago

I use cassandra to query the data, and I want all the query to use same cluster and session, so I used the following method:

lazy_static! {
    static ref SESSION: Session = {
        Cluster::default()
            .set_contact_points("127.0.0.1") //
                .expect("Failed to set_contact_points")
            .set_port(9042)
                .expect("Failed to set_port")
            .set_num_threads_io(8)
                .expect("Failed to set_num_threads_io")
            .connect()
                .expect("Failed to connect to the cluster")
    };
}

However, because the contact points are changing, different environments have different ipAddr, So I want to use std::env::args. Is this achievable? or similar usage that allows me to specify contact points when I execute the program?

KodrAus commented 5 years ago

Hi @pili2026 :wave:

So assuming you don’t want to try abstract away the source of your configuration from actual environment variables, or abstract the storage of your long-lived session from a static variable, you shouldn’t have any problem using std::env::args in a lazy_static. Your program will attempt to access that environment the first time you use your session, so assuming those variables won’t change during runtime everything should work ok.

pili2026 commented 5 years ago

Hi @KodrAus Thanks for reply, I didn’t expect this to be easy to use, I tested successfully, thanks

KodrAus commented 5 years ago

No problem! Please feel free to create new issues if you run into any troubles.