I have a crate that has Option.take()
as a core method (not that it could NOT be replaced by something else, but it is still there).
The use case is very simple. Let me give you an example (modified so it is not too specific for my use case) I have this struct:
pub struct NamedValues {
pub names: Vec<String>,
pub values: Option<Vec<f64>>,
}
Now, this struct allows me to add values as follows:
impl NamedValues{
fn push(&mut self, name: String, v: f64){
self.names.push(name);
self.values.push(v);
}
}
So, the two fields are VERY MUCH related to each other and therefore it makes sense to build them together.
Now, the reason this is not a HASH is twofold:
First—and I'm not including this in the example—every time there is a push()
, I'll check the data that is being input (e.g., I want it to be lower than the last element being input).
Second, because after building this structure, I want to separate the names
from the values
. I do this by using take()
. In my use case, the values
become the state of a simulation and therefore I want them to be easily cloned, copied, transferred, read and written. The names
, on the other hand, become useful only for writing the results afterwards (i.e., to keep note of what each value
means).
let mut values = named_values.take();
// Write down a CSV with results
println!("{}", &named_values.names);
loop {
update_values_through_highly_sofisticated_simulation(&mut values);
println!("{}", values);
}
and the result would be something like
name1, name2, name3
1, 2, 3
4, 5, 6
...