I have a large number of repeated data transformations that I'd like to DRY up as much as possible. e.g.
struct A {
first: Option<f32>,
second: i64,
...
}
let data = vec![A{None, 1}, A{Some(2.), 3}, ...];
Currently, I have fairly repetive code to calculate the mean of each field. e.g.
let mean_first = data.iter().filter(|a| a.first.is_some()).map(|a| a.first.unwrap() ).sum::<f32>() / data.length() as f32;
let mean_second = data.iter().map(|a| a.second).sum::<i64>() / data.length() as f32;
In reality, the struct has potentially hundreds of numeric fields of mixed and optional types, and I'd like to compute several types of statistics for each field. Is it possible to define a function that takes a Vec, and the name of a field member of T, and returns the mean for those members and handles both float and integer values, optional or not?
If there were a programmatic way to get a field by knowing it's string name, a solution might look like:
fn mean(vec: Vec<T>, field: String) -> f32 {
...
}
let mean_first = mean(data, "first");
let mean_second = mean(data, "second");
or more OO might look like
let mean_first = data.mean("first");
let mean_second = data.mean("second");
If not possible with a function, is a macro a good fit here?