gpt4 book ai didi

rust - 如何使用 rustc-env 标志指定环境变量?

转载 作者:行者123 更新时间:2023-11-29 08:34:25 32 4
gpt4 key购买 nike

我想设置 rustc-env=VAR=VALUE 以便我可以在我的代码中使用 env::var("VAR") 访问它。但是,我不清楚在哪里指定它。我可以在 Makefile 中设置环境变量 VAR 吗?

最佳答案

长话短说

build.rs

fn main() {
println!("cargo:rustc-env=VAR=VALUE");
}

src/main.rs

fn main() {
let var = env!("VAR");
}

documentation that you linked用于 Cargo 构建脚本:

The Rust file designated by the build command (relative to the package root) will be compiled and invoked before anything else is compiled in the package, allowing your Rust code to depend on the built or generated artifacts. By default Cargo looks up for "build.rs" file in a package root (even if you do not specify a value for build). Use build = "custom_build_name.rs" to specify a custom build name or build = false to disable automatic detection of the build script.

在同一页上,有一个 section that describes outputs of build.rs

All the lines printed to stdout by a build script are written to a file [...] Any line that starts with cargo: is interpreted directly by Cargo. This line must be of the form cargo:key=value, like the examples below:

cargo:rustc-env=FOO=bar

然后详细说明rustc-env:

rustc-env=VAR=VALUE indicates that the specified environment variable will be added to the environment which the compiler is run within. The value can be then retrieved by the env! macro in the compiled crate. This is useful for embedding additional metadata in crate's code, such as the hash of Git HEAD or the unique identifier of a continuous integration server.

env!是一个宏。


access it using env::var("VAR")

没有。 env::var用于读取程序运行时设置的环境变量,而不是程序编译时设置的。

另见:

关于rust - 如何使用 rustc-env 标志指定环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621642/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com