I have several structures with N (can be distinct) fields of type Option<f64>. I want with a single function to evaluate whether or not I keep small values (values < DELTA = 0.005) of these fields. For this, I must implement an iterator that captures only the desired N fields from the structures.
Let KeysValuesA and KeysValuesB be structures defined with distinct numbers of fields of type Option<f64> (N is equal to 3 and 4 respectively):
#[derive(Debug, Default, PartialEq, PartialOrd, Clone)]
struct KeysValuesA {
key_a : String,
key_b : u32,
key_c : Option<u16>,
value_a: Option<f64>,
value_b: Option<f64>,
value_c: Option<f64>,
}
#[derive(Debug, Default, PartialEq, PartialOrd, Clone)]
struct KeysValuesB {
key_a : String,
key_b : Option<u16>,
value_a: Option<f64>,
value_b: Option<f64>,
value_c: Option<f64>,
value_d: Option<f64>,
}
After implementing the trait:
trait AllValues {
fn all_values_vec(&mut self) -> Vec<&mut Option<f64>>;
fn all_values_arr<const N: usize>(&mut self) -> [&mut Option<f64>; N];
}
impl AllValues for KeysValuesA {
fn all_values_vec(&mut self) -> Vec<&mut Option<f64>> {
let values: Vec<&mut Option<f64>> = vec![
&mut self.value_a,
&mut self.value_b,
&mut self.value_c,
];
values
}
fn all_values_arr<const N: usize>(&mut self) -> [&mut Option<f64>; N] { todo!() }
}
impl AllValues for KeysValuesB {
fn all_values_vec(&mut self) -> Vec<&mut Option<f64>> {
let values: Vec<&mut Option<f64>> = vec![
&mut self.value_a,
&mut self.value_b,
&mut self.value_c,
&mut self.value_d,
];
values
}
fn all_values_arr<const N: usize>(&mut self) -> [&mut Option<f64>; N] { todo!() }
}
I use the iterator for the function, like that (DELTA is a constant):
fn despise_small_values_vec<T: AllValues>(keysvalues: &mut T) {
for value in keysvalues.all_values_vec() {
if value.unwrap_or(0.0).abs() < DELTA {
*value = None;
}
}
}
So I can implement iterator from Output: Vec<&mut Option<f64>>, but I cannot implement it from Output: array [&mut Option<f64>; N].
How to implement iterator for array [&mut Option<f64>; N] such that N can vary according to the Struct used?
And what would be the advantage of using array instead of using vector?
Follow the codes: Rust Playground