vector - Increment last element of Vec<usize> -


i have let mut stack: vec<usize> = vec![5, 7, 1] of varying length. @ point of program want increment last element of stack one. tried stack.last_mut().unwrap() += 1 (i know stack won't empty) compiler complains

error: binary assignment operation `+=` cannot applied 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 can first pop last element stack, increment , add again, there easier way?

dereference before incrementing:

fn main() {     let mut stack = vec![1, 3, 5];     *stack.last_mut().unwrap() += 1;     println!("{:?}", stack); } 

Comments