How to get Cargo package metadata (version, name, description) in a Rust program?
Hi everyone! I'm writing a CLI utility in Rust and I want it to display the program version when run with the `--version` flag. But I don't want to hardcode the string "0.1.0" in the code — that's inconvenient, the version should only be changed in `Cargo.toml`.
Problem: I can't figure out how to read data from `Cargo.toml` from within the Rust program itself. I tried using `std::fs::read_to_string("Cargo.toml")`, but this only works if the program is run from the project root, and after installation via `cargo install`, the `Cargo.toml` file is not located next to the binary.
Here's my current code, which of course doesn't work as intended:
```rust
fn main() {
let version = std::fs::read_to_string("Cargo.toml")
.ok()
.and_then(|s| {
s.lines()
.find(|l| l.starts_with("version"))
```
No answers yet.
Log in to leave an answer
Blogs