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);
}
                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
}
                        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