How do I assign a command line argument to a Static variable in Rust

Viewed 163

I am new to Rust. I am creating a Rust binary that takes a command line argument. I want to be able to use the command line argument string as a static constant string for the entirety of the application.

What is the right approach to doing that?

If I declare something static and I update it I am having to use unsafe everywhere I use it.

If I use lazy_static like below, I am not sure how to make the locally acquired &argv[1] accessible to a closure declared inside main

lazy_static! {
    static ref MYID: String = get_arg_value();
}

fn main() {

    let argsv: Vec<String> = std::env::args().collect();
    let get_arg_value = || -> String { argsv[1] }

}

1 Answers

Just put the code inside the lazy_static!:

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1]
    };
}

But then you'll get an error "cannot move out of index". So clone the string (it's one-time initialization so perf doesn't matter):

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1].clone()
    };
}

Note that you don't really need the Vec - you can work with the iterator:

lazy_static! {
    static ref MID: String = std::env::args().nth(1).unwrap();
}

Also note that it's better to use once_cell as it's going to be part of std.

Related