You return a borrowed value by changing the function signature to accept a string slice (&str) and return a string slice (&str) instead of String types. This avoids moving ownership and allows the caller to keep using 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);
println!("The first word is {}", word);
}