Skip to content

env! for non-string constants #1907

Closed
Closed
@jmegaffin

Description

@jmegaffin

There are some useful environment variables that are or could be non-string values, like CARGO_PKG_VERSION_*, NUM_JOBS, and DEP_*_*. Currently, however, they are only exposed to Rust as constant strings, not numbers, so it is impossible to do something like:

pub const VERSION_MAJOR: usize = env!("CARGO_PKG_VERSION_MAJOR");

You need to parse the string into an integer and then unwrap the result, which are both non-constant operations. If there were env!-like macros for boolean, integral, and fractional values and characters, then it would be possible to use them in new places like constant definitions, patterns, and eventually generics. It is possible to work around this in some cases by defining functions instead that internally parse the string into the desired type and using comparisons instead of pattern matching, but this is not ideal for ergonomics and potentially efficiency.


Of course, this would also be satisfied by making the appropriate standard library functions (str::parse, Option::unwrap) const fns, which would work for even user-defined types, but the macro solution could be implemented immediately without having to change any existing APIs. These macros could also be implemented as procedural macros, but support for this feature outside of deriving traits is poor as of the time of writing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions