011 Rust数组

Rust 数组

数组(Array)用一对中括号 [ ] 包括的相同类型且长度固定的数据。

数组的三要素:

  • 长度固定
  • 元素的类型必须相同
  • 依次线性排列(元素位置固定)

数组声明

方式一:类型推断

rust 复制代码
let array = [10, 20, 30, 40, 50]; // 推断元素类型和元素个数

方式二:明确元素类型和个数

rust 复制代码
let array:[i32; 5] = [10, 20, 30, 40, 50];

方式三:指定元素值和个数

rust 复制代码
let array= [5;10];  // 输出[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

数组元素访问

方式一:使用索引,索引从0开始

rust 复制代码
let arr = [10, 20, 30, 40];
let first = arr[0]; // 访问第一个元素 → 10
let third = arr[2]; // 访问第三个元素 → 30

索引越界检查

Rust 会在运行时检查索引有效性,越界访问会导致 panic:

rust 复制代码
let arr = [1, 2, 3];
// 编译通过但运行时报错:index out of bounds
let invalid = arr[5]; // ❌ panic: index 5 out of bounds

方式二:使用 get()方法【推荐】

使用 get()方法返回 Option<&T>,避免 panic:

rust 复制代码
let arr = ["a", "b", "c"];
match arr.get(2) {
    Some(val) => println!("Value: {}", val), // "Value: c"
    None => println!("Index out of bounds"),
}
let array= [5;10];
if let Some(val) = array.get(2) {
   println!("{:?}", val);  // 安全访问值,索引越界不会打印值
} 

多维数组访问

rust 复制代码
let matrix = [[1, 2], [3, 4], [5, 6]];
let element = matrix[1][0]; // 访问第二行第一列 → 3

方式三:通过切片访问

切片 (&[T]) 使用相同语法:

rust 复制代码
let arr = [10, 20, 30, 40];
let slice = &arr[1..3]; // [20, 30]
println!("{}", slice[1]); // 30

方式四:for...in迭代器遍历数组

rust 复制代码
let array= [5;10];
for item in array.iter(){
    println!("{}",item);        
} 

方式五:for...in索引下标访问

rust 复制代码
let array= [5;10];
for item in 0..array.len(){
    println!("{}",array[item]);        
}

方式六:while循环 + 索引下标

rust 复制代码
let array= [5;10];
let mut index = 0;
while index < 10 {
     println!("the value is: {}", array[index]);
     index += 1;        
}

方式七:loop循环 + 索引下标

rust 复制代码
let array= [5;10];
let mut index = 0;
loop {
    if index >= array.len() {
       break;
    }
    println!("the value is: {}", array[index]);
    index += 1;
}

想要修改数组元素的值,需要用mut关键字声明为可变数组。

rust 复制代码
let arr = [1,2,3,4,5]
// arr[0] = 10;  // 编译错误,arr是不可变数组
let mut arr2 = [10,20,30,40,50]
arr2[0] = 1;   // 正确,arr2为可变数组
相关推荐
@菜菜_达12 小时前
interact.js 前端拖拽插件
开发语言·前端·javascript
APIshop12 小时前
实战解析:苏宁易购 item_search 按关键字搜索商品API接口
开发语言·chrome·python
百***920213 小时前
java进阶1——JVM
java·开发语言·jvm
蓝桉~MLGT13 小时前
Python学习历程——Python面向对象编程详解
开发语言·python·学习
Evand J13 小时前
【MATLAB例程】2雷达二维目标跟踪滤波系统-UKF(无迹卡尔曼滤波)实现,目标匀速运动模型(带扰动)。附代码下载链接
开发语言·matlab·目标跟踪·滤波·卡尔曼滤波
larance13 小时前
Python 中的 *args 和 **kwargs
开发语言·python
Easonmax13 小时前
用 Rust 打造可复现的 ASCII 艺术渲染器:从像素到字符的完整工程实践
开发语言·后端·rust
lsx20240613 小时前
Rust 宏:深入理解与高效使用
开发语言
百锦再13 小时前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
小羊失眠啦.13 小时前
深入解析Rust的所有权系统:告别空指针和数据竞争
开发语言·后端·rust