我正在将一些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重写这样的代码,正确的/最不痛苦的方法是什么?
发布于 2014-08-25 20:04:05
问题1:条件表达式
因为配置标志可以解释为整数,所以它们可以用作变体数组中的索引。
// Configuration flag
static CONFIG_FLAG: uint = 1;
// Variants of any static type
type T = &'static str;
static VARIANT1: T = "True";
static VARIANT2: T = "False";
// Now you can select, but you have to invert either flag, or variants, or your brain
static SELECTED: T = [VARIANT1, VARIANT2][1 - CONFIG_FLAG];
fn main() {
println!("{}", SELECTED);
}备注:
类型bool的CONFIG_FLAG目前在数组索引中不工作,因为#5873问题,
// error: can't cast str to uint
static SELECTED: T = [VARIANT1, VARIANT2][1 - CONFIG_FLAG_BOOL as uint];因此,您必须再创建一个静态项,然后在条件项中使用它。
static CONFIG_FLAG_UINT: uint = CONFIG_FLAG_BOOL as uint;问题2:编译时字符串连接
简单的C宏很好地映射到了Rust宏中,所以您可以使用与C中相同的方法来进行字符串连接,唯一的区别是您必须显式地使用concat!而不是仅仅把文字放在一起。
#![feature(macro_rules)]
// Define new macro-string with name $name assembled from arguments $arg
macro_rules! define_str (
($name: ident, $($arg: expr), +)
=>
(macro_rules! $name (
() => (concat!($($arg), +))
));
)
// Some strings
define_str!(ROOT_DIR, "/root")
define_str!(SUB_DIR, ROOT_DIR!(), "/sub")
define_str!(FILE_NAME, SUB_DIR!(), "/file")
define_str!(NONSENSE, FILE_NAME!(), SUB_DIR!(), ROOT_DIR!())
fn main() {
println!("{}", FILE_NAME!());
println!("{}", NONSENSE!());
}备注:
我想将!()自动添加到define_str内部的宏名中,并添加如下所示的宏,
macro_rules! add_bang_and_parens (
($arg: ident) => ($arg!());
($arg: expr) => ($arg);
)但是,在宏模式中,基于“类型”的参数匹配似乎是不可能的。
https://stackoverflow.com/questions/25474152
复制相似问题