I have code which reads a config.toml file based on the environment name and provides all the config settings to the entire project.
const fn get_conf() -> toml::Value {
let file_name = match env::var("ENVIRONMENT") {
Ok(val) => val.to_lowercase(),
Err(_e) => "development".to_lowercase(),
};
let content = fs::read_to_string(format!("conf/{}.toml", file_name)).unwrap();
let conf: Value = toml::from_str(content.as_str()).unwrap();
conf
}
static mut CONFIG: toml::Value = get_conf();
I get an error:
error[E0658]: `match` is not allowed in a `const fn`
--> src/lib.rs:2:21
|
2 | let file_name = match env::var("ENVIRONMENT") {
| _____________________^
3 | | Ok(val) => val.to_lowercase(),
4 | | Err(_e) => "development".to_lowercase(),
5 | | };
| |_____^
|
= note: see issue #49146 <https://github.com/rust-lang/rust/issues/49146> for more information
This is solved in Rust nightly, but I don't want to use a nightly build for production. Is there any workaround for using a match or if condition in a const function?
From Rust 1.46 some core language features are now allowed in const fn.
const fn improvements
There are several core language features you can now use in a const fn:
if, if let, and match while, while let, and loop the && and || operators
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With