Getting the Cargo version into the Rust source code


The Cargo.toml file has the version number, the question is how to get that number into the Rust source code so as to stay DRY. Other languages have build systems that deal with constructing a configuration file, It seems I cannot find how to do the same with Cargo.


Cargo sets some environment variables:

CARGO_PKG_VERSION - The full version of your package.
CARGO_PKG_VERSION_MAJOR - The major version of your package.
CARGO_PKG_VERSION_MINOR - The minor version of your package.
CARGO_PKG_VERSION_PATCH - The patch version of your package.

You can access these variables in Rust using the builtin env! macro.

See for the full list of environment variables.


Sponditious. That looks very doable. Thanks muchly, I shall away and use. :slight_smile:


Where macros can’t help, the version-sync crate adds tests to remind you to update docs links and the README