如何将特征的关联类型用于常量泛型和数组的长度?



我有一个理想的情况,其结构如下:

pub struct ConstraintProperties<const COUNT: usize> {
particles: [ParticleReference; COUNT],
}
pub trait Constraint {
fn project(&self, particle_source: &mut [Particle], dt: f64, static_pass: bool);
}
pub trait ConstraintData {
const COUNT: usize;
fn properties(&self) -> ConstraintProperties<{ Self::COUNT }>;
fn constraint(&self, particles: [&Particle; { Self::COUNT }]) -> f64;
fn gradients(&self, particles: [&Particle; { Self::COUNT }]) -> [Vec3; { Self::COUNT }];
}
impl<C: ConstraintData> Constraint for C {
fn project(&self, particle_source: &mut [Particle], dt: f64, static_pass: bool) {
...
}
}

然而,我遇到了以下错误:;类型参数不能在const表达式中使用">

如何绕过这一点,以便使用特征的相关常数来管理常量泛型和特征函数所采用的数组长度?

在夜间,您可以使用#![feature(generic_const_exprs)]:

#![feature(generic_const_exprs)]
pub trait ConstraintData {
const COUNT: usize;
fn properties(&self) -> ConstraintProperties<{ Self::COUNT }>;
fn constraint(&self, particles: [&Particle; Self::COUNT]) -> f64;
fn gradients(&self, particles: [&Particle; Self::COUNT]) -> [Vec3; Self::COUNT];
}

但请注意,此功能是高度实验性的,不建议在生产中使用。

最新更新