Why slices are used in Rust - Performance Analysis
We want to understand how using slices affects the time it takes to work with parts of data in Rust.
How does using slices change the cost of accessing and processing data?
Analyze the time complexity of the following code snippet.
fn sum_slice(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers.iter() {
total += num;
}
total
}
fn main() {
let data = vec![1, 2, 3, 4, 5];
let part = &data[1..4];
println!("Sum: {}", sum_slice(part));
}
This code sums a part of a list using a slice, which is a view into the original data without copying it.
- Primary operation: Looping over the slice elements to add them.
- How many times: Once for each element in the slice.
As the slice size grows, the number of additions grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements in the slice.
Time Complexity: O(n)
This means the time to sum the slice grows linearly with the slice size.
[X] Wrong: "Using a slice copies the data, so it takes extra time."
[OK] Correct: Slices are just views into existing data, so no copying happens and no extra time is spent on that.
Understanding slices helps you explain efficient data access without copying, a key skill in writing fast and safe Rust code.
"What if we changed the slice to a vector copy? How would the time complexity change?"
Practice
let arr = [1, 2, 3, 4]; let slice = &arr[1..3];Solution
Step 1: Understand what a slice does
A slice is a reference to a part of a collection, like a section of an array, without copying the data.Step 2: Analyze the example code
The code&arr[1..3]creates a slice referencing elements at index 1 and 2, not a new array or deletion.Final Answer:
To access a part of a collection without copying the data -> Option AQuick Check:
Slices = references to parts of collections [OK]
- Thinking slices copy data
- Confusing slices with new arrays
- Assuming slices delete elements
arr in Rust?Solution
Step 1: Recall slice syntax in Rust
Rust slices are references, so you must use&before the range to create a slice.Step 2: Check each option
let slice = &arr[0..3]; uses&arr[0..3], which is the correct syntax. let slice = arr[0..3]; misses the reference, B uses invalid syntax, and C uses a non-existent method.Final Answer:
let slice = &arr[0..3]; -> Option DQuick Check:
Slice syntax = &array[start..end] [OK]
- Omitting & before the slice range
- Using invalid methods like slice()
- Using comma instead of range syntax
let arr = [10, 20, 30, 40, 50];
let slice = &arr[2..4];
println!("{:?}", slice);Solution
Step 1: Understand the slice range
The slice&arr[2..4]includes elements at index 2 and 3 (end index 4 is exclusive).Step 2: Identify elements at those indices
Index 2 is 30, index 3 is 40, so the slice contains [30, 40].Final Answer:
[30, 40] -> Option AQuick Check:
Slice range excludes end index [OK]
- Including the end index element
- Confusing indices with values
- Printing the whole array instead of slice
let arr = [1, 2, 3, 4]; let slice = arr[1..5];
Solution
Step 1: Check the slice range validity
The array has length 4, so index 5 is out of bounds causing an error.Step 2: Check slice syntax
The code misses the&reference operator needed to create a slice.Final Answer:
Slice range is out of bounds and missing reference operator -> Option BQuick Check:
Slice must be &array[start..end] within bounds [OK]
- Ignoring out of bounds index
- Forgetting & before slice
- Thinking brackets are wrong syntax
Solution
Step 1: Understand string slices and indexing
String slices&strare references to string data and support slicing with range syntax and&to get a slice.Step 2: Analyze each function signature and usage
fn print_first_three(s: &str) { println!("{}", &s[0..3]); } correctly takes&strand slices with&s[0..3]. fn print_first_three(s: String) { println!("{}", &s[0..3]); } takes ownership (String) but slices correctly. fn print_first_three(s: &String) { println!("{}", s[0..3]); } misses&before slice. fn print_first_three(s: &str) { println!("{}", s[0..3]); } slices without&, causing error.Final Answer:
fn print_first_three(s: &str) { println!("{}", &s[0..3]); } -> Option CQuick Check:
Use &str and &s[start..end] for safe string slices [OK]
- Using String instead of &str for slicing
- Omitting & before slice range
- Trying to slice without reference
Ready to prove it?
Pass the test and this pattern moves unknown
