Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the last item of an array?

Tags:

arrays

rust

Since arr is borrowed as mutable, the length of arr can't be gotten by calling len(). I'm stuck here, what's the right way to do it?

fn double_last(arr: &mut[i32]) -> &i32 {
    let last = &mut arr[arr.len() - 1];  // borrow checker error.
    //let last = &mut arr[3];            // fine
    *last *= 2;
    last
}

fn main() {
    let mut a = [1,2,3,4];
    println!("{}", double_last(&mut a));
    println!("{:?}", a);
}
like image 489
limon Avatar asked May 05 '16 05:05

limon


1 Answers

If you only need the last, you can use std::slice::last_mut

fn double_last(arr: &mut[i32]) -> &i32 {
    let last = arr.last_mut().unwrap();
    *last *= 2;
    last
}
like image 87
WiSaGaN Avatar answered Sep 25 '22 05:09

WiSaGaN