Rust: "borrowed value does not live long enough" when returning a &str from a function
Ask Question10
1 Answer
4
fn first_word(s: String) -> &str {
s.split(' ').next().unwrap()
}The compiler says the borrowed value does not live long enough. I just want the first word.
s is owned by the function and dropped when it returns, so a &str pointing into it would dangle. Either borrow the input:
fn first_word(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}or return an owned String:
fn first_word(s: String) -> String {
s.split(' ').next().unwrap_or("").to_string()
}