我目前正在开发一个简单的项目来让自己熟悉 Rust。我没有太多系统编程经验,但我希望学习!
我正在尝试创建一个矩阵结构,但我发现很难弄清楚应该如何存储数据。我觉得我应该能够使用数组。矩阵的大小必须在构造时定义,因此我希望可以将数组存储在堆栈上。
现在我的代码如下所示:
use std::ops::Mul;
use std::ops::Add;
use std::ops::Div;
struct Matrix {
cols: i32,
rows: i32,
// Of course this doesn't work!
data: [f32; ..cols*rows]
}
// Below here are a bunch of stub methods.
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(self, m: f32) -> Matrix {
return self;
}
}
impl Mul<Matrix> for Matrix {
type Output = Matrix;
fn mul(self, m: Matrix) -> Matrix {
// Will use Strassen algorithm if large, traditional otherwise
return self;
}
}
impl Add<Matrix> for Matrix {
type Output = Matrix;
fn add(self, m: Matrix) -> Matrix {
return self;
}
}
impl Div<f32> for Matrix {
type Output = Matrix;
fn div(self, f: f32) -> Matrix {
return self;
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用Vec.
struct Matrix {
cols: i32,
rows: i32,
data: Vec<f32>
}
impl Matrix {
fn new(cols: i32, rows: i32) -> Matrix {
Matrix {
cols: cols,
rows: rows,
data: vec![0.0; cols * rows]
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不想将数据存储在堆上,您可以将其设置Matrix为动态大小的类型,但这很难做到,并且不受真正支持。请参阅有关该主题的 Reddit 主题。
如果您不想使用 aVec但可以将数据存储在堆上,则可以使用盒装切片 ( Box<[f32]>)。请参阅Vec::into_boxed_slice参考资料 中的一种创建方法。
当然,如果你真的不想使用堆,你可以Matrix为不同大小的矩阵创建不同的类型。这就是板条箱nalgebra 的作用。