首页 > 解决方案 > 将动态整数映射到 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()) }
        }
    }
}

但是,我需要考虑很多长度......有没有更符合人体工程学的方法来做到这一点?

标签: rustruntimetraitsconst-generics

解决方案


您可以使用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())
}

推荐阅读