Lesson 9 of 20
Slices
Slices
A slice is a reference to a contiguous sequence of elements in a collection. Slices do not have ownership.
Slice Syntax
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; // [2, 3] — indices 1 and 2
let all = &a[..]; // [1, 2, 3, 4, 5]
let first3 = &a[..3]; // [1, 2, 3]
let last2 = &a[3..]; // [4, 5]
Slice Type
The type of a slice of i32 values is &[i32]. Functions that accept slices work with both arrays and vectors:
fn sum(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
let arr = [1, 2, 3];
let vec = vec![1, 2, 3];
sum(&arr); // works
sum(&vec); // also works
String Slices
String slices (&str) are references into a String or string literal:
let s = String::from("hello world");
let hello = &s[0..5]; // "hello"
let world = &s[6..11]; // "world"
Common Slice Methods
slice.len() // number of elements
slice.is_empty() // true if len() == 0
slice.contains(&x) // true if x is in slice
slice.iter() // iterator over &T
slice.windows(n) // overlapping windows of size n
slice.chunks(n) // non-overlapping chunks of size n
Your Task
rotate_left(v: &[i32], k: usize) -> Vec<i32>— rotate the slice left by k positions (elements wrap around).max_subarray_sum(arr: &[i32]) -> i32— find the contiguous subarray with the largest sum (Kadane's algorithm).contains_duplicate(v: &[i32]) -> bool— return true if any value appears more than once.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.