如何修改数组的最后一项? [英] How to modify the last item of an array?

查看:111
本文介绍了如何修改数组的最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于借来了 arr 的可变性,因此无法通过调用 len()来获取 arr 的长度.我被困在这里,正确的方法是什么?

  fn double_last(arr:& mut [i32])->& i32 {让last =& mut arr [arr.len()-1];//借用检查器错误.//让last =& mut arr [3];//美好的*最后* = 2;最后的}fn main(){让mut a = [1,2,3,4];println!("{}",double_last(& mut a));println!("{:?}",a);} 

解决方案

希望通过引入非词汇生存期以及随之而来的不久的将来的更改(似乎可以解决?)来解决此问题.>

不过,现在,您可以通过将计算拆分为以下内容来满足借阅检查器的要求:

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

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

解决方案

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];

这篇关于如何修改数组的最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆