Rust Tutorial: Arrays and Slices in Rust
Work with fixed-size arrays and slices in Rust.
Concepts in this chapter
You will learn and practice:
- **Arrays** — fixed size, same type; `[T; N]` e.g. `[i32; 5]`
- **Slices** — `&[T]` view into a contiguous sequence; length not known at compile time
- **Vec** — heap-allocated, growable vector; use for dynamic collections
- **Indexing** — arr[i]; panics on out of bounds
- **Iteration** — for x in arr.iter() or for x in &v
---
Arrays
```rust
let arr: [i32; 3] = [10, 20, 30];
println!("{}", arr[1]); // 20
println!("{}", arr.len());
```
---
Vec
```rust
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
v.push(3);
println!("{}", v.len());
```
---
Slices
A slice `&[T]` is a reference to a contiguous region. Arrays and Vecs coerce to slices:
```rust
let arr = [1, 2, 3];
let slice: &[i32] = &arr[1..]; // [2, 3]
```
---
What's Next?
Next: **HashMap** — key-value storage.
What you'll learn in this Rust arrays and slices in rust tutorial
This interactive Rust tutorial has 3 hands-on exercises. Estimated time: 15 minutes.
- Create and Print Array — Create an array of three integers: 10, 20, 30. Print each element on its own line using a for loop.
- Vec push and len — Create a Vec of strings with Vec::new(). Push "apple", "banana", "cherry". Print the length, then print the element at i…
- Sum of Array — Compute the sum of all elements in `let arr = [1, 2, 3, 4, 5];` and print the result.
Rust Arrays and Slices in Rust concepts covered
- Concepts in this chapter
- Arrays
- Vec
- Slices
- What's Next?