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为可变数组
相关推荐
invicinble几秒前
springboot的核心实现机制原理
java·spring boot·后端
人道领域9 分钟前
SSM框架从入门到入土(AOP面向切面编程)
java·开发语言
铅笔侠_小龙虾10 分钟前
Flutter 实战: 计算器
开发语言·javascript·flutter
全栈老石26 分钟前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
2的n次方_27 分钟前
Runtime 执行提交机制:NPU 硬件队列的管理与任务原子化下发
c语言·开发语言
space621232734 分钟前
在SpringBoot项目中集成MongoDB
spring boot·后端·mongodb
2501_944711431 小时前
JS 对象遍历全解析
开发语言·前端·javascript
凡人叶枫1 小时前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发
Tony Bai1 小时前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang
小糯米6012 小时前
C++顺序表和vector
开发语言·c++·算法