Reputation: 1655
I am learning Rust by doing matrix math. The very first step is to create a new matrix of rows and columns, and initializes the matrix with the elements in values in row-major order.
If I want to pass the input matrix value vector as &[T], but I am not sure how to initialize the matrix with the elements values.
pub struct Matrix<T> {
data: Vec<T>,
row: usize,
col: usize,
}
/// Creates a new matrix of `row` rows and `col` columns, and initializes
/// the matrix with the elements in `values` in row-major order.
pub fn new(row: usize, col: usize, values: &[T]) -> Matrix<T> {
Matrix {
data: *values, // ??
row: row,
col: col,
}
}
fn main() {
let x = Matrix::new(2, 3, &[-2, -1, 0, 1, 2, 3]);
let y = Matrix::new(2, 3, &[0, 0, 0, 0, 0, 0]);
// z = x + y;
}
Based on this post , &[T] is a reference to a set of Ts laid out sequentially in memory. Does that mean it is not possible to convert all the "slice" from pointers to vector type? And the only way to do is to use a loop to do deref of each item and store them in a new vector?
Upvotes: 0
Views: 246
Reputation: 88536
It is possible, but not via *
(dereferencing). You see, &[T]
is something borrowed, so you can't keep it. The type Matrix<T>
owns its data
. You can't simply borrow something (values
) and then give it away as if you own it ("here, Matrix, take these values, you can keep them").
What you can do is to copy the borrowed data and store it as an owned type (Vec<T>
). You can now give away this copy of the data, because you own it. Converting from borrowed to owned can be done by the to_owned()
method, for example:
pub fn new(row: usize, col: usize, values: &[T]) -> Matrix<T> {
Matrix {
data: values.to_owned(),
// ^^^^^^^^^^^
row: row,
col: col,
}
}
Upvotes: 5