Can't figure out how to elegantly change the field of the struct which is embedded into a vector of Option. Here is the variation of the code i tried to write, but it does not work. I thought of extracting the value with take(), changing the field and then inserting the Option back into the Vec, but this does not seem to be a performant solution...
Could you, please, suggest a good one?
fn main() {
let mut vec_try = vec![Some(Val {val_int: 8, val_str: String::from("try1")}), Some(Val {val_int:20, val_str: String::from("try2")}), Some(Val {val_int:33, val_str: String::from("try3")})];
if let Some(value) = &vec_try[1] {
Some(Val {val_int: 22, ..value});
}
println!("The value is: {:?}", vec_try[1]);
}
#[derive(Debug)]
struct Val {
val_int: u8,
val_str: String,
}
Not however that this doesn't allow you to use the struct update syntax, since this would move the value out of reference (even if to put it back right away).
Thank you for the reply! This is interesting... But i do not understand why is that.
I would think about take() operations as: 1) move the pointer to struct somewhere, 2) assign None to the current array[index], 3) change the field, 4) assign the pointer to struct back into array[index].
As opposed to just following a pointer (aka struct->field) and changing the field of the struct.
Please, explain where my understanding goes wrong...
Again, not sure i understand...
If the struct is on the heap, how is it moved out and back in without a "pointer"?
Does move occur in this case as well:
if let Some(value) = &mut vec_try[1] {
value.val_int = 22;
}
Thank you, it is much more clear now.
But there was a reply above saying that the move occurs in any case. You say that this is not true - i.e., i see some disagreement between what you and RedDocMD wrote.
Thus, was my original guess that the modification of the struct in place is more performant correct?
Move occurs in any case if you can't get with only replacing some fields, i.e. if you need the whole struct to get the new struct. If you can replace it field-by-field, this can be done in-place, without move.