There are a number of environment variables available during the build of a binary.
One of them is the CARGO_PKG_VERSION
variable that contains the version number as written in the Cargo.toml
file.
Using the env! macro we can extract the value during the build phase of the compilation and we can include it on our code either as a constant using the const keyword or we can make it a regular variable either explicitely making it a static variable or letting Rust figure out the type.
The difference will be the location where the value is stored.
The code
examples/embed-version-number/src/main.rs
const VERSION: &str = env!("CARGO_PKG_VERSION");
fn main() {
let explicit_type_version: &'static str = env!("CARGO_PKG_VERSION");
let implicit_type_version = env!("CARGO_PKG_VERSION");
println!("Constant version {VERSION}");
println!("Explicit version {explicit_type_version}");
println!("Implicit version {implicit_type_version}");
}
Cargo.toml with the version number
examples/embed-version-number/Cargo.toml
[package]
name = "embed-version-number"
version = "1.2.3"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Note
I'd go with the const
.
If you only need to have a --version
flag you can tell Clap to create a --version flag.