Rust
Beginner
1 min read
Slices and the Borrow Checker
Example
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == b' ' {
return &s[..i];
}
}
s // whole string is one word
}
fn sum_slice(nums: &[i32]) -> i32 {
nums.iter().sum()
}
fn main() {
// String slices
let sentence = String::from("hello world");
let word = first_word(&sentence);
println!("first word = {word}");
// sentence.clear(); // compile error: mutable borrow while 'word' is live
// &str works for both String refs and literals
let literal = "foo bar baz";
println!("first word of literal = {}", first_word(literal));
// Array slice
let arr = [1, 2, 3, 4, 5];
println!("sum of arr = {}", sum_slice(&arr));
// Vec slice — &[T] accepts both arrays and vecs
let v: Vec<i32> = vec![10, 20, 30];
println!("sum of vec = {}", sum_slice(&v));
// Mutable slice
let mut data = [3, 1, 4, 1, 5, 9, 2, 6];
data.sort();
println!("sorted = {:?}", &data);
// Sub-slice
let middle = &data[2..6];
println!("middle slice = {:?}", middle);
}