Trait russell_lab::AsArray1D [−][src]
Expand description
Defines a trait to handle 1D arrays
Example
use russell_lab::AsArray1D;
fn sum<'a, T, U>(array: &'a T) -> f64
where
T: AsArray1D<'a, U>,
U: 'a + Into<f64>,
{
let mut res = 0.0;
let m = array.size();
for i in 0..m {
res += array.at(i).into();
}
res
}
// heap-allocated 1D array (vector)
let x = vec![1.0, 2.0, 3.0];
assert_eq!(sum(&x), 6.0);
// heap-allocated 1D array (slice)
let y: &[f64] = &[10.0, 20.0, 30.0];
assert_eq!(sum(&y), 60.0);
// stack-allocated (fixed-size) 2D array
let z = [100.0, 200.0, 300.0];
assert_eq!(sum(&z), 600.0);Review
Arrays
Arrays have type [T; N] and are a fixed-size list of elements of the same type.
Arrays are allocated on the stack.
Subscripts start at zero.
let x = [1.0, 2.0, 3.0]; // a: [f64; 3]Shorthand for initializing each element to 0.0:
let x = [0.0; 20]; // a: [f64; 20]Vectors
Vectors are dynamic or “growable” arrays of type Vec<T>.
Vectors are allocated on the heap.
We can create vectors with the vec! macro:
let v = vec![1.0, 2.0, 3.0]; // v: Vec<f64>Slices
Slices have type &[T] and are a reference to (or “view” into) an array.
Slices allow efficient access to a portion of an array without copying.
A slice is not created directly, but from an existing variable.
Slices have a length, can be mutable or not, and in behave like arrays:
let a = [0.0, 1.0, 2.0, 3.0, 4.0];
let middle = &a[1..4]; // A slice of a: just the elements 1.0, 2.0, and 3.0Required methods
Implementations on Foreign Types
Defines a heap-allocated 1D array (vector)
Defines a heap-allocated 1D array (slice)
Defines a stack-allocated (fixed-size) 1D array