tl;dr 如何像在 C 预处理器中那样在 Rust 中使用“编译时设置变量”?
在C中,预处理器宏语言允许设置预处理器变量,可以在以后的预处理中使用。
这是 C 语言中的一个人为示例,它检查一次魔法变量列表,然后保存该结果以供以后在预处理器阶段使用。
#if defined(_MSC_EXTENSIONS) || defined(__IOS__)
#define IMPORT_MAGIC_LIB 1
#else
#define IMPORT_MAGIC_LIB 0
#endif
// ... later ...
#if IMPORT_MAGIC_LIB == 1
#include "magic_lib.h"
#else
#include "plain_lib.h"
#endif
我想在 Rust 中做类似的事情(伪造的伪代码;不会编译)
#[if(any(target_os = "windows", target_os = "ios"))]
#set IMPORT_MAGIC_LIB : bool = true;
#[else]
#set IMPORT_MAGIC_LIB : bool = false;
#[endif]
// ... later ...
#[if(IMPORT_MAGIC_LIB)]
use ::magic_lib as my_lib;
#[else]
use ::plain_lib as my_lib;
#[endif]
我想在 Rust 中做的是检查一些特殊的“魔法”列表一次 (
any(target_os = "windows", target_os = "ios")
) 并在宏处理编译阶段在其他地方重新使用该检查。我想避免在多个地方重复 target_os
的列表。