能否遍历Rust结构体的关联常量?有没有可用的crate?
在Rust中遍历结构体的关联常量是否可行?
原生Rust本身没有提供直接枚举结构体关联常量的能力——关联常量是编译期确定的实体,Rust没有内置的运行时反射机制来自动遍历它们。不过有两种可行的解决方案:
1. 手动用宏维护常量列表
可以通过宏来同时定义常量和对应的遍历数组,这样新增常量时只需要在宏里添加,不用手动同步遍历列表:
struct MyStruct; macro_rules! define_my_constants { ($($name:ident = $value:expr),* $(,)?) => { impl MyStruct { $(pub const $name: &str = $value;)* // 自动生成包含所有常量的数组 pub const ALL_CONSTANTS: &[&str] = &[$($value),*]; } }; } // 在这里添加/修改常量 define_my_constants! { MyConstant1 = "Hello", MyConstant2 = "Stackoverflow", } // 遍历示例 fn main() { for val in MyStruct::ALL_CONSTANTS { println!("{}", val); } }
2. 使用第三方crate
有专门的crate可以帮你在编译期收集静态项,比如inventory:
首先在Cargo.toml中添加依赖,然后通过宏注册要遍历的常量,之后就能统一收集并遍历:
use inventory::{collect, submit}; struct MyStruct; impl MyStruct { const MyConstant1: &str = "Hello"; const MyConstant2: &str = "Stackoverflow"; } // 把每个常量注册到inventory中 submit! { &str => MyStruct::MyConstant1 } submit! { &str => MyStruct::MyConstant2 } // 遍历注册的常量 fn main() { // 方式1:针对特定类型遍历 for constant in inventory::iter::<&str>() { println!("{}", constant); } }
注意新增常量时,需要同步添加对应的submit!宏调用,否则无法被收集到。
内容的提问来源于stack exchange,提问作者arandompersonontheinternet
相关产品推荐
相关产品推荐

