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 standard --version
flag, and I'd like the implementation to read the version of the package from Cargo.toml
so I don't have to maintain it in two places. I can imagine there are other reasons someone might want to access Cargo metadata from the program as well.
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
- Destructure a vector into variables and give away
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
- How do I initialize an opaque C struct when using
- What's the most idiomatic way to test two Opti
The built-crate helps with serializing a lot of Cargo's environment without all the boilerplate.
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):You can access environment variables using the
env!()
macro. To insert the version number of your program you can do this:If you want your program to compile even without Cargo, you can use
option_env!()
: