How can a Rust program access metadata from its Cargo package?

前端 未结 2 1810
南旧
南旧 2020-12-04 06:56

How do you access a Cargo package\'s metadata (e.g. version) from the Rust code in the package? In my case, I am building a command line tool that I\'d like to have a standa

相关标签:
2条回答
  • 2020-12-04 07:06

    Cargo passes some metadata to the compiler through environment variables, a list of which can be found in the Cargo documentation pages.

    The compiler environment is populated by fill_env in Cargo's code. This code has become more complex since earlier versions, and the entire list of variables is no longer obvious from it because it can be dynamic. However, at least the following variables are set there (from the list in the docs):

    CARGO_MANIFEST_DIR
    CARGO_PKG_AUTHORS
    CARGO_PKG_DESCRIPTION
    CARGO_PKG_HOMEPAGE
    CARGO_PKG_NAME
    CARGO_PKG_REPOSITORY
    CARGO_PKG_VERSION
    CARGO_PKG_VERSION_MAJOR
    CARGO_PKG_VERSION_MINOR
    CARGO_PKG_VERSION_PATCH
    CARGO_PKG_VERSION_PRE
    

    You can access environment variables using the env!() macro. To insert the version number of your program you can do this:

    const VERSION: &'static str = env!("CARGO_PKG_VERSION");
    
    // ...
    
    println!("MyProgram v{}", VERSION);
    

    If you want your program to compile even without Cargo, you can use option_env!():

    const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
    
    // ...
    
    println!("MyProgram v{}", VERSION.unwrap_or("unknown"));
    
    0 讨论(0)
  • 2020-12-04 07:27

    The built-crate helps with serializing a lot of Cargo's environment without all the boilerplate.

    0 讨论(0)
提交回复
热议问题