Hi, so this might be a quite newbie question, but nevertheless I did not find sensible answer. Given that I'm given a vector of values v
, let's assume 5 of them. I need to modify the middle one based on conditions regarding the whole array. A pseudo code would look like this:
let mut v = vec![Some(1), None, Some(2), Some(3), None];
match v.get_mut(2){
Some(&mut Some(ref mut x)) => {
match v.get(0) {
Some(& Some(ref y)) => {
if *y < 10{
*x = v.get(3).unwrap().unwrap() + 5;
} else {
*x = v.get(3).unwrap().unwrap() + 2;
}
},
_ => ()
}
},
_ => ()
}
Of course this will not compile for the obvious reasons of borrowing. My question is, what is the proper way to this in rust as I could not figured it out myself so far. I thought of 3 possible solution, but I think both are ugly:
- For each match copy the value from the vector and use that inside the match, so that you are not really borrowing
v
- Make boolean variables which describe which path you take, use the match with borrows only to set these variables
The third solution is sort of presented below:
let mut v = vec![Some(1), None, Some(2), Some(3), None];
if match v.get(2){
Some(&Some(_)) => true,
_ => false
} && match v.get(0) {
Some(&Some(ref y)) => true,
_ => false
} {
v[2] = if v.get(0).unwrap().unwrap() < 10 {
Some(v.get(3).unwrap().unwrap() + 5)
} else {
Some(v.get(3).unwrap().unwrap() + 2)
};
};
So I after all this I wanted to know if you guys have any suggestions for better ways, and how to think about this in rust. Cheers!