rust / beginner
Snippet
Array Slicing in Rust
Slices in Rust provide a view into a contiguous sequence of elements. The syntax &[start..end] creates a slice from start (inclusive) to end (exclusive). Slices are references to portions of arrays or vectors, allowing efficient access without copying data. Functions can accept slices to work with any contiguous sequence.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {let numbers = [1, 2, 3, 4, 5];// Full slicelet entire = &numbers[..];println!("Entire array: {:?}", entire);// First three elementslet first_three = &numbers[0..3];println!("First three: {:?}", first_three);// Last two elements using array_lenlet len = numbers.len();let last_two = &numbers[len - 2..len];println!("Last two: {:?}", last_two);// Slice function parameterprint_slice(&numbers[1..4]);}fn print_slice(slice: &[i32]) {println!("Slice: {:?}", slice);}
Breakdown
1
&numbers[..]
Creates a slice of the entire array
2
&numbers[0..3]
Creates a slice from index 0 to 3 (elements 1, 2, 3)
3
fn print_slice(slice: &[i32])
Function that accepts a slice of i32 values