Array slices
- Rust course
- Beginner
- Lesson 56/115
- 4 min
Slice part of an array or vector with &[T].
Array slices
Arrays and vectors can be sliced too; the result has the type &[T]:
let a = [10, 20, 30, 40, 50];
let orta: &[i32] = &a[1..4];
println!("{:?} {}", orta, orta.len()); // [20, 30, 40] 3
let v = vec![1, 2, 3];
let hepsi: &[i32] = &v; // &Vec<i32> → &[i32]A slice knows its length and has methods such as iter, contains, first and last.
Mutable slices
&mut v[a..b] gives a &mut [T]; elements can be changed through the slice but the length can't (there is no push):
let mut v = vec![1, 2, 3, 4];
let d = &mut v[1..3];
d[0] = 20;
d.reverse();
println!("{:?}", v); // [1, 3, 20, 4]sort, reverse, swap and fill are slice methods.
Practice Middle part
For let v = vec![3, 1, 4, 1, 5, 9];, take the slice &v[2..5]. Print the slice and the sum of its elements (iter().sum::<i32>()).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let v = vec![3, 1, 4, 1, 5, 9];
let orta = &v[2..5];
let t: i32 = orta.iter().sum();
println!("{:?} {}", orta, t);
}Expected output
[4, 1, 5] 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For <code>let v = vec![5, 6, 7]; let d = &v[1..];</code>, what is <code>d.first()</code>?
- Some(&6) Correct answer
- Some(&5)
- 6
- None
Explanation: The slice starts at index 1; first returns a reference to the first element inside an Option.
2 The middle three
let a = [10, 20, 30, 40, 50];
let orta = &a[____]; // [20, 30, 40]
let a = [10, 20, 30, 40, 50];
let orta = &a[1..4]; // [20, 30, 40]
Explanation: The range 1..4 takes indexes 1, 2 and 3.
3 Method and result (on [4, 1, 5])
| Term | Meaning |
|---|---|
len() |
3 |
first() |
Some(&4) |
last() |
Some(&5) |
contains(&1) |
true |