Get version and application name?

I have created standard Rust application via cargo new --bin.
And it has in Cargo.toml:

name = "my-app"
version = "0.1.0"

How I can get access to theses values from main function:

fn main() {
   if std:env::args().nth(1) == Some("--version") {
     let name = ...;
     let version = ...;
      println!("App {name}, Version {version}");

Does rustc + cargo provides some kind of access to theses values in Cargo.toml, so I can use them in Rust code?

I use clap for that, namely the crate_version and crate_name macros. They are just wrappers around calls to env!("CARGO_PKG_VERSION") and env!("CARGO_PKG_NAME"), if you don't want to pull clap in as a dependency.

1 Like

There's the list of environment variables Cargo sets for crates, which can be read using the env! macro, or the functions in std::env.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.