#ident #concat #name #concatenate #combine #generate

concat-idents

允许连接多个标识符并在任何地方使用它们

7个稳定版本

1.1.5 2023年6月14日
1.1.4 2022年10月31日
1.1.3 2021年7月4日
1.1.2 2021年1月12日
1.0.0 2020年8月4日

#43 in 过程宏

Download history 5450/week @ 2024-04-22 6672/week @ 2024-04-29 9195/week @ 2024-05-06 8830/week @ 2024-05-13 7314/week @ 2024-05-20 6726/week @ 2024-05-27 8318/week @ 2024-06-03 8715/week @ 2024-06-10 7377/week @ 2024-06-17 7205/week @ 2024-06-24 6888/week @ 2024-07-01 8553/week @ 2024-07-08 8500/week @ 2024-07-15 10086/week @ 2024-07-22 14733/week @ 2024-07-29 11086/week @ 2024-08-05

44,932每月下载量
93 个crate中(直接使用48个) 使用

MIT/Apache

15KB
184

concat-idents!

crates.io docs.rs licence

此crate提供了一个简单易用的宏。

用法

基本用法

use concat_idents::concat_idents;

concat_idents!(fn_name = foo_, _, bar {
       fn fn_name() {
           // --snip--
       }
});

foo__bar();

允许的标识符部分

concat_idents!(fn_name = _, __ { /* underscores */ });
concat_idents!(fn_name = foo, _bar { /* identifiers */ });
concat_idents!(fn_name = "foo", "bar" { /* strings */ });
concat_idents!(fn_name = 'f', 'o', 'o' { /* characters */ });
concat_idents!(fn_name = foo, 1, bar, 2 { /* integers */ });
concat_idents!(fn_name = true, false { /* booleans */ });
concat_idents!(fn_name = "enum", bar { /* quoted reserved keywords (recommended way) */ });
concat_idents!(fn_name = r#struct, bar { /* escaped reserved keywords (not recommended, since some keywords produce error) */ });

生成测试

macro_rules! generate_test {
   ($method:ident($lhs:ident, $rhs:ident)) => {
       concat_idents!(test_name = $method, _, $lhs, _, $rhs {
           #[test]
           fn test_name() {
               let _ = $lhs::default().$method($rhs::default());
           }
       });
   };
}

#[derive(Default)]
struct S(i32);

impl Add<i32> for S {
   type Output = S;
   fn add(self,rhs: i32) -> Self::Output { S(self.0 + rhs) }
}

impl Sub<i32> for S {
   type Output = S;
   fn sub(self,rhs: i32) -> Self::Output { S(self.0 - rhs) }
}

generate_test!(add(S, i32));
generate_test!(sub(S, i32));

错误

如果传入的标识符语法意外

  1. 其中一个标识符无效
concat_idents!({});
concat_idents!(ident {});
concat_idents!(ident =  {});
concat_idents!(= foo, bar {});
concat_idents!(ident = foo, bar);
...
  1. 将抛出编译错误
concat_idents!(ident = true {});        // identifiers cannot consist of only one bool 
concat_idents!(ident = 1 {});           // identifiers cannot consist of only one int
concat_idents!(ident = 1, foo {});      // identifiers cannot start with an int
concat_idents!(ident = foo, 1.0 {});    // identifiers cannot contain floats
concat_idents!(ident = "enum");         // identifiers cannot consist of only one reserved keyword
concat_idents!(ident = r#struct);       // identifiers cannot consist of only one reserved keyword
concat_idents!(ident = " space");       // identifiers cannot contain spaces
concat_idents!(ident = "foo-bar🧨");    // identifiers can only contain [a-zA-Z0-9_]
...

依赖项

~270–720KB
~17K SLoC