【发布时间】:2014-08-24 17:04:22
【问题描述】:
我正在将一些 C 代码移植到 Rust,并且该代码包含很多类似这样的内容:
#define CONFIG_FLAG_NUMBER_23 1
#define THIS 10
#define THAT 11
#define THIS_AND_THAT (THIS + THAT)
#if CONFIG_FLAG_NUMBER_23
#define THIS_OR_THAT THIS
#else
#define THIS_OR_THAT THAT
#endif
#define ROOT_DIR "/root"
#define FILE_ONE ROOT_DIR "/file_one"
#define FILE_TWO ROOT_DIR "/file_two"
我决定删除宏并用常量表达式替换它们,但在 Rust 中这样做的尝试并不是很成功:
static CONFIG_FLAG: bool = true;
static THIS: int = 10;
static THAT: int = 11;
static THIS_AND_THAT: int = THIS + THAT; // Okay, it works
// 1: Conditions
static THIS_OR_THAT: int = CONFIG_FLAG ? THIS : THAT; // Doesn't work, no conditional operator
static THIS_OR_THAT: int = if CONFIG_FLAG { THIS } else { THAT }; // Doesn't work, "if" is not basic enough for compile time
// 2: Strings
static ROOT_DIR: &'static str = "/root";
static FILE_ONE: &'static str = ROOT_DIR + "/file_one"; // Doesn't work, static strs can't be Added
static FILE_TWO: String = ROOT_DIR.to_string() + "/file_two"; // Don't even think about allocations in constant expressions!
static FILE_THREE: &'static str = concat!(ROOT_DIR, "/file_three"); // Doesn't work, concat! works only with literals
用 Rust 重写此类代码的正确/最不痛苦的方法是什么?
【问题讨论】:
-
@mafso 好的,我会将我的编辑重新格式化为答案,但我仍然对其他(也许更好)解决方案感兴趣。
-
将标题更改为更相关