I have a let mut stack: Vec<usize> = vec![5, 7, 1] of varying length. At some point of the program I want to increment the last element of the stack by one. I tried stack.last_mut().unwrap() += 1 (I know the stack won't be empty) but the compiler complains
error: binary assignment operation `+=` cannot be applied to type `&mut _` [--explain E0368]
 --> src/main.rs:3:5
3 |>     stack.last_mut().unwrap() += 1;
  |>     ^^^^^^^^^^^^^^^^^^^^^^^^^
error: invalid left-hand side expression [--explain E0067]
 --> src/main.rs:3:5
3 |>     stack.last_mut().unwrap() += 1;
  |>     ^^^^^^^^^^^^^^^^^^^^^^^^^
Of course I can first pop the last element from the stack, increment it and add it again, but is there an easier way?
Dereference before incrementing:
fn main() {
    let mut stack = vec![1, 3, 5];
    *stack.last_mut().unwrap() += 1;
    println!("{:?}", stack);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With