How to Return a Reference from a Function in Rust

Return a reference in Rust by using string slices (&str) to avoid moving ownership and allow shared access to data.

Return a reference by changing the function signature to accept and return string slices (&str) instead of owned String types. This avoids moving ownership and allows the caller to retain the original data.

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);
}