在Rust的运行时使用环境变量填充静态/常量 [英] Populating a static/const with an environment variable at runtime in Rust
问题描述
我正在尝试在服务启动时从系统环境中加载密码和敏感数据.我尝试了多种不同的方法,但似乎无法找出在Rust中执行此操作的正确方法.
I'm trying to load passwords and sensitive data from the system's environment when my service starts up. I've tried a number of different ways but can't seem to figure out the right way to do this in Rust.
const PASSWORD: String = var("PASSWORD").unwrap();
不起作用,因为method calls in constants are limited to constant inherent methods
. static
也是如此(显然错误是静态的).
Doesn't work because method calls in constants are limited to constant inherent methods
. The same applies to static
(except the error says statics, obviously).
我看到的另一种方式是
const PASSWORD: &'static str = env!("PASSWORD");
但是问题在于它会在编译时定义,因为env!
是一个宏(至少这是我的理解).
But the problem with that is it will be defined at compile time as env!
is a macro (at least that is my understanding).
我还考虑过将对var("...").unwrap()
的调用仅包装在一个函数中,但是该解决方案并不适合我,而且还允许在整个运行时更改值,并且在服务启动时不对其进行验证.
I also considered simply wrapping the call to var("...").unwrap()
in a function but that solution doesn't really sit right with me, and would also allow the values to change throughout runtime AND not validate them when the service starts.
您可以说我是Rust的新手.如果您在回答中不能仅解释如何在运行时加载const/static,还可以解释为什么我在做的是愚蠢的和错误的,我将不胜感激:)
As you can tell I'm new to Rust. I'd really appreciate if in your answer you could not just explain how to load the const/static at runtime but also explain why what I'm doing is dumb and wrong :)
推荐答案
const
和static
在Rust中扮演不同的角色.
const
and static
fill different roles in Rust.
const
不仅表示常量,还表示 compile-time 常量,该值是在编译时确定的,并写入程序的只读存储器中.它不适合您的用例.
const
does not only mean a constant, it means a compile-time constant, a value determined at compile-time and inscribed in the read-only memory of the program. It is not suitable for your usecase.
static
表示全局变量,其生存期将遍及整个程序.它可能是可变的,在这种情况下,必须为Sync
以避免并行修改.必须从常量中初始化static
变量,以便从程序开始就可以使用它.
static
means a global variable, with a lifetime that will span the entire program. It may be mutable, in which case it must be Sync
to avoid concurrent modifications. A static
variable must be initialized from a constant, in order to be available from the start of the program.
那么,如何在运行时读取变量并使变量可用?好吧,一个干净的解决方案是完全避免全局变量.
So, how to read a variable at run-time and have it available? Well, a clean solution would be to avoid globals altogether...
...但由于它很方便,因此有一个包装箱: lazy_static!
.
... but since it can be convenient, there is a crate for it: lazy_static!
.
use std::env::var;
use lazy_static::lazy_static;
lazy_static! {
static ref PASSWORD: String = var("PASSWORD").unwrap();
}
fn main() {
println!("{:?}", *PASSWORD);
}
第一次访问该变量时,将执行该表达式以加载其值,然后将该值存储起来并可用,直到程序结束为止.
On first access to the variable, the expression is executed to load its value, the value is then memorized and available until the end of the program.
这篇关于在Rust的运行时使用环境变量填充静态/常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!