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为可变数组
相关推荐
闲人编程3 小时前
使用Celery处理Python Web应用中的异步任务
开发语言·前端·python·web·异步·celery
托比-马奎尔3 小时前
Redis7内存数据库
java·redis·后端
Lei活在当下3 小时前
【业务场景架构实战】6. 从业务痛点到通用能力:Android 优先级分页加载器设计
前端·后端·架构
千里马-horse3 小时前
Async++ 源码分析3---cancel.h
开发语言·c++·async++·cancel
你的人类朋友3 小时前
什么是基础设施中间件
前端·后端
K_i1345 小时前
指针步长:C/C++内存操控的核心法则
java·开发语言
渡我白衣5 小时前
C++ :std::bind 还能用吗?它和 Lambda 有什么区别?
开发语言·c++·c++20
胖咕噜的稞达鸭5 小时前
算法入门:专题攻克主题一---双指针(1)移动零 复写零
c语言·开发语言·c++·算法
郝学胜-神的一滴5 小时前
Effective Python 第38条:简单的接口应该接受函数,而不是类的实例
开发语言·python·软件工程