-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
env_or_default macro #48952
Comments
Alternatively we could just make const VERSION: &str = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown version"); |
Agreed. We can't make |
I don't think it is uncommon to require different semantics than just a default for Having something like fn nonempty_env(name: &str) -> Option<String> {
match env::var(name) {
Ok("") | Err(env::VarError::NotPresent) => None,
Err(e) => panic!("error looking up {}: {}", name, e),
Ok(s) => Some(s),
}
} So for me, |
@hanna-kruppe now that rust-lang/rfcs#2342 has been merged, can we make |
I think so. |
Saw #76330, but it was closed because destructors cannot run in const contexts just yet |
I'm new to Rust. I'm using rust 1.60.0. I'm trying to use this code (PLAYGROUND HERE): pub const VERSION: &'static str = option_env!("VERSION").unwrap_or_else(|| "dev"); but I'm getting this error:
Can you help me understand what's wrong with it? |
The diagnostic should actually just tell you that the function is not a const fn. But we messed up a bit, so you get a different error first. You just can't do this yet that way, you have to match manually and implement the some and none arms of the match yourself. |
I have a use case for this that's not covered by include!(core::option_env!("DATA_ROOT").unwrap_or("empty_data/mod.rs")); This doesn't compile because |
Tracking issue for This issue also contains a nice workaround: pub const VERSION: &str= match option_env!("VERSION") {
Some(v) => v,
None => "dev",
}; |
Might I suggest closing this in favour of #91930? It allows doing this with |
That does not cover the use case in my previous comment. |
Maybe it's best to adapt |
I assume |
Closing this in favour of #91930 |
That doesn't work for includes |
I find my self doing something like this quite often:
I think it would be nice to have a
env_or_default
macro that defaults to a fallback string at compile time if the environment variable cannot be found. I'm thinking of something likeI know the runtime cost isn't that high but if it can be done at compile time, it should be done.
The text was updated successfully, but these errors were encountered: