运行时使用环境变量填充静态

运行时使用环境变量填充静态

本文介绍了在 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();

不起作用,因为常量中的方法调用仅限于常量固有方法.这同样适用于 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 :)

推荐答案

conststatic 在 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 运行时使用环境变量填充静态/常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:17