Return a reference in Rust by using &str slices for parameters and return types to share data without moving ownership.
Return a reference by declaring the function parameter and return type as &str slices instead of String to avoid moving ownership.
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[..]
}
Returning a reference lets you share data without copying it or taking ownership, which keeps the original data alive. Think of it like pointing to a specific page in a book rather than photocopying the whole page or taking the book home. You use this pattern when you need to inspect a part of a string or collection without modifying it.