'How to convert 3-dimensional array of fixed size to a reference-style?
I work with 3-dimensional arrays of fixed size. For the first time I used passing by value.
fn some_func(matrix: [[[f64;Z];Y];X]) {// body}
fn main() {
let m = [[[0.0;Z];Y];X];
some_func(m);
}
It means copying all elements and is bad for efficiency. So I decided to remake code by using references.
If I do it like this:
fn some_func(matrix: &[[[f64;Z];Y];X]) {// body}
fn main() {
let m = [[[0.0;Z];Y];X];
some_func(&m);
}
it won't copy variable "matrix", but will still copy matrix[i]. To avoid copying, as I understand, &[&[&[f64]]] type of function argument should be used. But... How can I convert [[[f64;Z];Y];X] to &[&[&[f64]]] to match the function signature with the argument being passed?
Or the only way is to use reference-notation while initialization, and even store the array as a reference to array of references (it is a field of a structure, in fact)?
Solution 1:[1]
They are not copied. Just having a reference & to the outer one should be enough:
fn printer(l: &[[usize; 1]; 1]) {
println!("{}", &(l[0]) as *const _ as usize);
}
fn main() {
let l = [[1]];
println!("{}", &(l[0]) as *const _ as usize);
printer(&l);
}
Outputs:
140725001518400
140725001518400
It means that it doesn't matter if you access from the original one or the &, you get access to the same inner structures.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Netwave |
