You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何高效修改Vec内最后一个数组元素?

问题解决:修改Vec中最后一个数组元素

你的代码无法修改最后一个元素的核心原因是:Vec::last()返回的是不可变引用(Option<&[i8;3]>),Rust的借用规则禁止通过不可变引用修改数据。要实现修改操作,需要使用Vec::last_mut()方法——它会返回可变引用(Option<&mut [i8;3]>),让你能合法修改数组内的元素。

修正后的完整代码:

fn main() {
    let mut test_vec: Vec<[i8; 3]> = vec![];
    test_vec.push([1, 2, 3]);
    test_vec.push([4, 5, 6]);
    match test_vec.last_mut() {
        Some(v) => {
            v[2] = 0;  // 现在可正常修改
        }
        None => {}
    }
    test_vec.push([7, 8, 9]);
    match test_vec.last_mut() {
        Some(v) => {
            v[1] = 0;  // 此处也能正常修改
        }
        None => {}
    }

    for entry in test_vec {
        println!("{entry:?}");  // 会输出 [1, 2, 3], [4, 5, 0] 和 [7, 0, 9]
    }
}

关键改动说明

  • 把test_vec.last()替换为test_vec.last_mut(),获取指向最后一个元素的可变引用
  • 基于可变引用,可直接对数组的索引位置赋值修改

内容的提问来源于stack exchange,提问作者Blindschleiche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:04:57