【问题标题】:Map dynamic integers to const integers将动态整数映射到 const 整数
【发布时间】:2021-05-05 09:57:17
【问题描述】:

我需要根据运行时参数调整同一结构的变体的内部长度。结构是通用定义的,仅在长度上有所不同。我能想到的唯一解决方案是使用匹配语句:

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()) }
        }
    }
}

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

【问题讨论】:

    标签: rust runtime traits const-generics


    【解决方案1】:

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

    【讨论】:

    • 这很有用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多