Rust 编程语言强大的编译器可以让它在编译阶段时就去做完许多其它编程语言在运行阶段才能进行的工作,像是 Rust 的标准函数库,就有提供一个 concat 宏,可以将任意数量定数(literal)直接串接成生命周期为 'static 的字符串切片(&'static str)。
例如以下代码:
const ABC: &str = concat!("test", 10, 'b', true);
ABC 是一个类型为 &'static str 的常数,其值等同于 "test10btrue"。
对于函数库(library)的开发,concat 宏可能用不太到,但是如果是在开发应用程序(application),就很有机会需要在代码中撰写大量的自然语句,concat 宏就可以用来「分段」这些语句,让程序比较容易维护,且在运行时又不会有多余的性能开支(overhead)。
不过在实务上,concat 宏用起来并不是很方便,因为它不能够自动在每个定数之间、之前或是之后自动添加其它的字符串(或是定数)。例如以逗号和空格 , 来分隔每个定数,就只能自行在原本的每个定数间撰写 , ,像是下面这个代码:
const ABC: &str = concat!("test", ", ", 10, ", ", 'b', ", ", true);
以上程序,ABC 常数的值等同于 "test, 10, b, true"。
Concat With
「Concat With」是笔者开发的套件,可以用以扩充标准函数库内的 concat 宏的功能,让它可以在每个定数的之间、之前或是之后自动添加其它的字符串(或是定数)。
Crates.io
Cargo.toml
宏的使用方法
concat
这个 concat_with crate,提供了与标准函数库中的 concat 宏同名的宏,用法兼容于标准函数库中的 concat 宏。但是,concat_with 的 concat 宏在撰写定数之前,可以使用 with、prefix、suffix 关键字来分别设置每个定数的之间、之前或是之后要自动添加什么字符串(或是定数)。
例如以逗号和空格 , 来分隔每个定数,代码可以这样写:
const ABC: &str = concat_with::concat!(with ", ", "test", 10, 'b', true);
再例如,以换行字符 \n 来分隔每个定数,并在每个定数前添加 Someone says: ,代码可以这样写:
const ABC: &str = concat_with::concat!(with "\n", prefix "Someone says: ", "Hello.", "Nice to meet you!");
以上程序,ABC 常数的值为 "Someone says: Hello.\nSomeone says: Nice to meet you!"。
concat_line
concat_line 宏算是 concat!(with "\n", ...) 的语法糖(syntactic sugar),可以省下使用 concat 宏时撰写 with "\n" 的麻烦。
例如:
const ABC: &str = concat_with::concat_line!(prefix "Someone says: ", "Hello.", "Nice to meet you!");
以上程序,ABC 常数的值同样为 "Someone says: Hello.\nSomeone says: Nice to meet you!"。
concat_impl
concat_impl 宏可以用来创建我们自己的宏,像是 concat_line 宏那样在串接定数的同时以特定的定数作分隔,且支持前缀和后缀的插入。
#[doc(hidden)]
pub use concat_with::{concat, concat_impl}; // re-export `concat!` and `concat_impl!` if your custom macros use `#[macro_export]`
concat_impl! {
#[macro_export]
/// Concatenates literals into a static string slice separated by a comma, `,`. Prefixes and suffixes can also be added.
concat_with_comma => ", ",
#[macro_export]
/// Concatenates literals into a static string slice separated by a colon, `:`. Prefixes and suffixes can also be added.
concat_with_colon => ':',
}
assert_eq!("test, 10, b, true", concat_with_comma!("test", 10, 'b', true));
assert_eq!("test:10:b:true", concat_with_colon!("test", 10, 'b', true));
