rust / intermediate
Snippet
Slices: Working with Portions of Data
Slices let you reference a contiguous sequence of elements within a collection without taking ownership. The slice type is written as &[T] for an array or &str for string slices. String slices are UTF-8 encoded and any byte access must account for character boundaries. Slices are passed by reference to avoid copying data.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn first_word(s: &str) -> &str {let bytes = s.as_bytes();for (i, &item) in bytes.iter().enumerate() {if item == b' ' {return &s[0..i];}}s}fn main() {let s = String::from("hello world");let word = first_word(&s);let arr = [1, 2, 3, 4, 5];let slice: &[i32] = &arr[1..4];println!("Slice: {:?}", slice);let s2 = "embedded string";let part = &s2[0..8];println!("Part: {}", part);}
Breakdown
1
fn first_word(s: &str) -> &str
Function takes a string slice and returns a string slice pointing to the first word
2
let slice: &[i32] = &arr[1..4]
Creates a slice of array elements at indices 1, 2, and 3. Type annotation shows it's a reference to a sequence of i32
3
let part = &s2[0..8]
String slice from byte 0 to 8. Must split on valid UTF-8 character boundaries