One of the main features of Rust is the borrow checker. Now I found a problem that I cannot solve because I need to mutate after immutable borrow. I am looking for workarounds or alternative solutions for what I want to do, preferably idiomatic methods. The code below is a simplified rewrite of something from C++, where it worked. I am calculating something and saving values in a vector for later analysis. The simplest way is to initialize the "Analysis"-struct with a reference of where to look at for later analysis. Once I am finished calculating new values and storing them in the vector I tell the Analysis-object to check it. I would like to know either how to achieve this or in a more general way, if it is at all a good idea. If not, why is it bad design? (the code below is just an example and does not compile as it is.)
struct Analysis {
curve_segment: &[f64],
local_maxima: u32,
local_minima: u32,
// ...
}
impl Analysis {
pub fn new(curve_segment: &[f64]) {
Analysis {
curve_segment,
local_maxima: 0,
local_minima: 0,
// ...
}
}
pub fn check_segment(&mut self) {
for sample in &self.curve_segment {
// check if maximum or minimum change local_maxima/-minima accordingly
}
}
}
fn main() {
let mut segment: Vec<f64> = vec![0.0; 1000];
let analysis = Analysis::new(&segment);
for _ in 0..number_of_segments {
for i in 0..segment.len() {
let some_value = // do some calculation;
segment[i] = some_value; // does not work because segment is already borrowed to 'analysis'.
}
analysis.check_segment();
}
}