1 个不稳定版本
0.1.2 | 2020年7月25日 |
---|
#462 在 过程宏
每月下载量:281
在 6 个crate中(通过 const_env--value)使用
14KB
175 行
const_env
注意:这是一个小型分支,它添加了一个用于检索环境变量值的宏。它应该被合并到上游,此crate是临时的,将不会更新。
动机
您的目标:您想在编译时根据环境变量定义代码中的各种常量。
您的问题:在今天的Rust中,只能对&'static str
常量进行此类操作。
const MY_STR: &'static str = env!("SOME_ENV");
您无法类似地初始化其他类型,如常量u32
、bool
或其他原始类型。参见问题和解决方案。最终,一旦支持在const fn
中运行parse
和unwrap
,您将能够这样做,但到目前为止,此crate提供了一个您现在就可以使用的简单解决方案。
用法
添加依赖项。
[dependencies]
const_env = "0.1"
在您的文件顶部导入from_env!
宏。
use const_env::from_env;
使用宏在构建时根据环境变量覆盖常量的值。
#[from_env]
const FOO: u32 = 123;
// This test will PASS if invoked as `FOO=456 cargo test`
#[test]
fn test() {
assert_eq!(456, FOO);
}
默认情况下,该宏查找与其附加的常量同名的一个环境变量。
// Use `FOO=true cargo build` to configure the value.
#[from_env]
const FOO: bool = false;
但您也可以显式指定一个名称。
// Use `BAR=true cargo build` to configure the value.
#[from_env("BAR")]
const FOO: bool = false;
您在源代码中分配的表达式作为环境变量不存在时的默认值。
// If env var FOO is not set then the FOO constant will have the default value of '🦀'.
#[from_env]
const FOO: char = '🦀';
支持const
和static
声明。
// Both of these may be set by `FOO=abc BAZ=def cargo build`.
#[from_env]
const FOO: &'static str = "hello";
#[from_env("BAZ")]
static BAR: &'static [u8] = b"world";
支持类型
字符串!
#[from_env]
const FOO: &'static str = "hello";
// example: `FOO=abc cargo build`
// results in:
const FOO: &'static str = "abc";
字节字符串!
#[from_env]
const FOO: &'static [u8] = b"hello";
// example: `FOO=world cargo build`
// results in:
const FOO: &'static [u8] = b"world";
字节!
#[from_env]
const FOO: u8 = b'⚙';
// example: `FOO=🦀 cargo build`
// results in:
const FOO: u8 = b'🦀';
字符!
#[from_env]
const FOO: char = '⚙';
// example: `FOO=🦀 cargo build`
// results in:
const FOO: car = '🦀';
各种形状和大小的整数!
#[from_env]
const FOO: u32 = 123;
#[from_env]
const BAR: i64 = 456;
#[from_env]
const BAZ: usize = 0;
// example: `FOO=321 BAR=-456 BAZ=1usize cargo build`
// results in:
const FOO: u32 = 321;
const BAR: i64 = -456;
const BAZ: usize = 1usize;
各种形状和大小的浮点数!
#[from_env]
const FOO: f32 = 123.0;
#[from_env]
const BAR: f64 = 456.0;
#[from_env]
const BAZ: f32 = 0.0;
// example: `FOO=321.0 BAR=-456.0 BAZ=1f32 cargo build`
// results in:
const FOO: f32 = 321.0;
const BAR: f64 = -456.0;
const BAZ: f32 = 1f32;
布尔值!
#[from_env]
const FOO: bool = false;
// example: `FOO=true cargo build`
// results in:
const FOO: bool = true;
已知限制
- 仅支持顶层
const
和static
声明。
替代方案
依赖项
~1.5MB
~34K SLoC