Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment last element of Vec<usize>

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?

like image 255
Pyfisch Avatar asked Oct 27 '25 09:10

Pyfisch


1 Answers

Dereference before incrementing:

fn main() {
    let mut stack = vec![1, 3, 5];
    *stack.last_mut().unwrap() += 1;
    println!("{:?}", stack);
}
like image 106
Shepmaster Avatar answered Oct 28 '25 22:10

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!