Rust 程序如何从其 Cargo 包访问元数据? [英] How can a Rust program access metadata from its Cargo package?

查看:36
本文介绍了Rust 程序如何从其 Cargo 包访问元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从包中的 Rust 代码访问 Cargo 包的元数据(例如版本)?就我而言,我正在构建一个命令行工具,我想要一个标准的 --version 标志,并且我想要实现从 读取包的版本Cargo.toml 所以我不必在两个地方维护它.我可以想象还有其他原因可能有人想从程序中访问 Cargo 元数据.

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.

推荐答案

Cargo 通过环境变量将一些元数据传递给编译器,其列表可以在 货物文档页面.

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

编译环境由fill_env.这段代码自早期版本以来变得更加复杂,整个变量列表不再明显,因为它可以是动态的.但是,至少在那里设置了以下变量(来自 文档中的列表):

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

您可以使用 env!() 访问环境变量代码> 宏.要插入程序的版本号,您可以这样做:

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);

如果你希望你的程序在没有 Cargo 的情况下也能编译,你可以使用 option_env!():

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"));

这篇关于Rust 程序如何从其 Cargo 包访问元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆