Populating a static/const with an environment variable at runtime in Rust

前端 未结 1 1372
遇见更好的自我
遇见更好的自我 2021-01-05 09:07

I\'m trying to load passwords and sensitive data from the system\'s environment when my service starts up. I\'ve tried a number of different ways but can\'t seem to figure o

相关标签:
1条回答
  • 2021-01-05 09:28

    const and static fill different roles in Rust.

    const does not only mean a constant, it means a compile-time constant, a value determined at compile-time and inscribed in the read-only memory of the program. It is not suitable for your usecase.

    static means a global variable, with a lifetime that will span the entire program. It may be mutable, in which case it must be Sync to avoid concurrent modifications. A static variable must be initialized from a constant, in order to be available from the start of the program.

    So, how to read a variable at run-time and have it available? Well, a clean solution would be to avoid globals altogether...

    ... but since it can be convenient, there is a crate for it: lazy_static!.

    use std::env::var;
    use lazy_static::lazy_static;
    
    lazy_static! {
        static ref PASSWORD: String = var("PASSWORD").unwrap();
    }
    
    fn main() {
        println!("{:?}", *PASSWORD);
    }
    

    On first access to the variable, the expression is executed to load its value, the value is then memorized and available until the end of the program.

    0 讨论(0)
提交回复
热议问题