How to modify the last item of an array?

余生颓废 提交于 2021-02-18 12:14:09

问题


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

回答1:


This will hopefully be fixed with the introduction of non-lexical lifetimes and the accompanying changes soon into the future (seems like it could be solved?).

For now though, you can satisfy the borrow checker by splitting that calculation out:

let n = arr.len() - 1;
let last = &mut arr[n];



回答2:


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
}


来源:https://stackoverflow.com/questions/37043067/how-to-modify-the-last-item-of-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!