Add Path to `std::env::VarError::NotPresent`

Unfortunately, this would be a breaking change, because VarError is a pub enum and not #[non_exhaustive], so adding a field to VarError::NotPresent or adding a new variant would break existing matches.

On the other hand, there is reason to consider overhauling the environment access API due to memory safety issues:

If that were done, a new error type could be included as part of the new API. The existing VarError is not Copy and already contains an OsString, so this would not remove any of its properties; but the new interface would either need a generic error type, or to copy the error, since the signature of env::var is

pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError>

and the K must be either moved as-is into the error value, or copied into an OsString. The advantage of copying is simplicity and not exposing implementation-detail argument types, but it would be wasteful in the case where code is checking for the existence of environment variables and not stopping on error (e.g. imagine some moderately-frequently-called code which checks for an environment variable every time).

2 Likes