Trait russell_lab::AsArray2D[][src]

pub trait AsArray2D<'a, U: 'a> {
    fn size(&self) -> (usize, usize);
fn at(&self, i: usize, j: usize) -> U; }
Expand description

Defines a trait to handle 2D arrays

Example

use russell_lab::AsArray2D;

fn sum<'a, T, U>(array: &'a T) -> f64
where
    T: AsArray2D<'a, U>,
    U: 'a + Into<f64>,
{
    let mut res = 0.0;
    let (m, n) = array.size();
    for i in 0..m {
        for j in 0..n {
            res += array.at(i, j).into();
        }
    }
    res
}

// heap-allocated 2D array (vector of vectors)
const IGNORED: f64 = 123.456;
let a = vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0, IGNORED, IGNORED, IGNORED],
    vec![5.0, 6.0],
];
assert_eq!(sum(&a), 21.0);

// heap-allocated 2D array (aka slice of slices)
let b: &[&[f64]] = &[
    &[10.0, 20.0],
    &[30.0, 40.0, IGNORED],
    &[50.0, 60.0, IGNORED, IGNORED],
];
assert_eq!(sum(&b), 210.0);

// stack-allocated (fixed-size) 2D array
let c = [
    [100.0, 200.0],
    [300.0, 400.0],
    [500.0, 600.0],
];
assert_eq!(sum(&c), 2100.0);

Required methods

Returns the (m,n) size of the array

Returns the value at (i,j) indices

Implementations on Foreign Types

Defines a heap-allocated 2D array (vector of vectors)

Notes

  • The number of columns is defined by the first row
  • The next rows must have at least the same number of columns as the first row

Defines a heap-allocated 2D array (slice of slices)

Notes

  • The number of columns is defined by the first row
  • The next rows must have at least the same number of columns as the first row

Defines a stack-allocated (fixed-size) 2D array

Implementors