简体   繁体   中英

Equivalent of -DPREPROC_VAR for rust/cargo

I have a const variable that I need to be hardcoded at runtime but configurable at compile time. In C/C++ style preprocessors one can typically tell the compile -DPREPROC_VAR and guard the definition with an #ifndef like

#ifndef MAX_TRHEADS
#define MAX_THREADS 1000
#endif

In rust I have

// Doesn't actually work because I need a usize and `env!` returns `&str`
const MAX_THREADS: usize = std::env!("MYLIB_MAX_THREADS");

but I can't figure out how to set a default value for it. I tried setting MYLIB_MAX_THREADS in the [env] section in Cargo.toml but it didn't work.

env! require the variable to be here so have a default value make no sense. However option_env! it could make sense:

const MAX_THREADS: &'static str = {
    if let Some(x) = std::option_env!("MYLIB_MAX_THREADS") {
        x
    } else {
        "42"
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM