rust - 将动态整数映射到 const 整数
问题描述
我需要根据运行时参数调整同一结构的变体的内部长度。结构是通用定义的,仅在长度上有所不同。我能想到的唯一解决方案是使用 match 语句:
pub struct Foo<const L: usize> {
data: [i32; L],
}
impl<const L: usize> Foo<L> {
pub fn new() -> Self {
Self { data: [0; L] }
}
}
pub trait FooTrait {
fn new_len_foo(&self, len: usize) -> Box<dyn FooTrait>;
}
impl<const L: usize> FooTrait for Foo<L> {
fn new_len_foo(&self, len: usize) -> Box<dyn FooTrait> {
match len {
2 => { Box::new(Foo::<2>::new()) },
3 => { Box::new(Foo::<3>::new()) },
4 => { Box::new(Foo::<4>::new()) },
_ => { Box::new(Foo::<1>::new()) }
}
}
}
但是,我需要考虑很多长度......有没有更符合人体工程学的方法来做到这一点?
解决方案
您可以使用seq_macro生成代码:
fn new_len_foo(&self, len: usize) -> Box<dyn FooTrait> {
seq!(L in 2..=24 {
if len == L { return Box::new(Foo::<L>::new()); }
});
Box::new(Foo::<1>::new())
}
推荐阅读
- javascript - 显示动态生成的输入字段的输入值
- python - 尝试在python中使用循环进行矩阵向量和矩阵矩阵乘法
- reactjs - 如何从 1 个组件中的两个端点获取数据?
- python - Python定义具有其他变量类型的变量
- java - 你如何在java中四舍五入一个双用户输入值?
- python - 在 Python 中删除二叉树节点。为什么 self != parent.left 或 parent.right?
- powerbi - 为什么平均值不适用于 power bi dax
- visual-studio-code - 有没有办法摆脱 VS 代码中浏览器评论扩展的模糊预览?
- c++ - 如何使用自定义错误消息使概念失败 (C++20)
- mdx - 使用日期小于的 MDX 获取数据