#proc-macro #array #fields #struct #struct-fields #accessing #procedural

named-array

一个用于将结构体字段作为数组访问的过程宏

2个版本

0.1.1 2024年5月25日
0.1.0 2024年5月25日

#502过程宏

MIT/Apache

10KB
142

此crate提供了named_array derive宏,允许您将结构体字段视为数组元素进行访问。它提供了IndexIndexMut的实现,将usize索引转换为按出现顺序的字段。

所有字段的类型必须相同,并且书写一致。例如,如果一个字段是Option<()>,另一个是core::option::Option<()>,代码将被拒绝。这是因为类型信息在宏展开时不存在,所以无法确认两个是否指向同一类型。

如果索引超出范围,索引将导致panic。

示例

#[derive(named_array)]
struct Example {
    a: u32,
    b: u32,
    c: u32,
}

let example = Example { a: 1, b: 2, c: 3 };
assert_eq!(example[0], example.a);
assert_eq!(example[1], example.b);
assert_eq!(example[2], example.c);

元组结构体

这也可以与元组结构体一起使用。但是,您可能更愿意使用struct Foo([u32; 3])而不是struct Foo(u32, u32, u32)

#[derive(named_array)]
struct Example(u32, u32, u32);
let example = Example(1, 2, 3);
assert_eq!(example[0], example.0);
assert_eq!(example[1], example.1);
assert_eq!(example[2], example.2);

依赖

~280–730KB
~17K SLoC