Env! return empty string for undefined env variable


I'm faily new to Rust and i'm facing some behavior which seems to contradict the official rust documentation.

Here's my piece of code


fn main() { 
    println!("DESCRIPTION => {:?}", DESCRIPTION);
    println!("CARGO_PKG_HOMEPAGE => {:?}", env!("CARGO_PKG_HOMEPAGE"));




name = "minimal"
version = "0.1.0"
edition = "2018"


But the documentation for env! state that

If the environment variable is not defined, then a compilation error will be emitted.

I am missing something ?

It seems that Cargo always sets all the env variables it exposes to crate, but by default they are empty.

thanks, it's indeed seems to be happening here.
But i find it a pity for the usefulness of option_env! macro.

As a side question, does something like unwrap_non_empty_string_or exist in Rust ?

match maybe_string {
   Some(s) if !s.is_empty() => s,
   _ => String::from("some default value")

You can make an extension trait to add it to all Options.

Only not panic, but some default value (the suffix _or in method name hints on this).

Ok, sorry to be late.

Sorry to be late.

Only not panic , but some default value (the suffix _or in method name hints on this)

I'm confused, can you be more explicit ?

In general unwrap/expect (so panicking) functions are handy for prototypes, but for long range solutions they are not good idea. In this very case, panicking on unthrusted input (which is an env variable) is rather bud idea. In production code panicking should happen only on unreachable code.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.