Borrowing with slices works by creating a reference to a contiguous sequence of elements within a collection without taking ownership of the whole collection. You create a slice by specifying a range or using the .. syntax, which borrows the underlying data for the duration of the reference.
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 my_string = String::from("hello world");
let word = first_word(&my_string);
println!("The first word is {}", word);
}