如何创建包含具有较大尺寸的纳代尔矩阵的结构?

时间:2018-11-09 12:45:34

标签: generics rust

我想创建一个struct,其中包含一个nalgebra::MatrixN大的U1

extern crate nalgebra as na;

use na::{DimName, DimNameAdd, DimNameSum, MatrixN, U1};

pub struct Homogenous<D: DimName>
where
    D: DimNameAdd<U1>,
{
    mat: na::MatrixN<f32, DimNameSum<D, U1>>,
}

我收到以下错误:

error[E0277]: cannot multiply `<<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value` to `<<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value`
 --> src/main.rs:9:5
  |
9 |     mat: na::MatrixN<f32, DimNameSum<D, U1>>,
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `<<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value * <<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value`
  |
  = help: the trait `std::ops::Mul` is not implemented for `<<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value`
  = help: consider adding a `where <<D as na::DimNameAdd<na::U1>>::Output as na::DimName>::Value: std::ops::Mul` bound
  = note: required because of the requirements on the impl of `na::allocator::Allocator<f32, <D as na::DimNameAdd<na::U1>>::Output, <D as na::DimNameAdd<na::U1>>::Output>` for `na::DefaultAllocator`

尝试遵循该错误消息会导致兔子洞出现下一个特征错误消息。我看过nalgebra的API,其中不包含如此复杂的特征链。例如to_homogenous方法。我不确定我的方法是否正确。

还有特征Dim和相应的DimAddDimSum,但是由于nalgebra的这一部分并未真正记录,因此

我不知道我是否走对了路,或者我想做的事是否有可能。

1 个答案:

答案 0 :(得分:3)

This post为我指明了正确的方向。在nalgebra中这样做的方法有些复杂:

extern crate nalgebra as na;

use crate::na::{Dim, DimName, DimNameAdd, DimNameSum, MatrixN, U1, DefaultAllocator};
use crate::na::allocator::Allocator;

pub struct Homogenous<D: Dim + DimName>
where
    D: DimNameAdd<U1>,
    DefaultAllocator: Allocator<f32, DimNameSum<D, U1>, DimNameSum<D, U1>>,
{
    mat: MatrixN<f32, DimNameSum<D, U1>>,
}

希望这些类型的通用操作在Rust和nalgebra的未来版本中变得更加符合人体工程学,因为这些相当繁琐的类型注释需要经常重复。

顺便说一句,仅将这些通用类型存储在结构中仍然需要DefaultAllocator

extern crate nalgebra as na;

use crate::na::{Dim, DimName, MatrixN, DefaultAllocator};
use crate::na::allocator::Allocator;

pub struct Homogenous<D: Dim + DimName>
where
    DefaultAllocator: Allocator<f32, D, D>,
{
    mat: MatrixN<f32, D>,
}