rust / intermediate
Snippet
Slices and Range Operations
Slices are views into contiguous sequences without ownership. The &[T] syntax represents a borrowed slice, while &mut [T] allows modification. Range syntax [start..end] creates sub-slices with exclusive end index. Slices carry a pointer and length, making them lightweight references. The contains method checks membership, and iter() provides enumeration. Slices enable flexible, zero-cost abstractions over collections.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn analyze_slice(slice: &[i32]) -> (usize, i32, i32) {let len = slice.len();let first = *slice.first().unwrap_or(&0);let last = *slice.last().unwrap_or(&0);(len, first, last)}fn main() {let arr = [10, 20, 30, 40, 50];let slice = &arr[1..4];println!("Slice: {:?}", slice);println!("Length: {}", slice.len());let (len, first, last) = analyze_slice(slice);println!("Analyzed: len={}, first={}, last={}", len, first, last);for (i, val) in arr.iter().enumerate() {print!("[{}:{}.{}] ", i, val, if arr[i..].contains(val) { "yes" } else { "no" });}}
Breakdown
1
&arr[1..4]
Creates slice from index 1 inclusive to 4 exclusive, containing [20, 30, 40]
2
fn analyze_slice(slice: &[i32])
Function takes borrowed slice, works with any contiguous sequence
3
slice.len()
Constant-time length retrieval without iteration
4
*slice.first().unwrap_or(&0)
Safely get first element or default value using pointer dereference