Rust mentions that nothing can be mutable borrowed WHILE it is immutably borrowed. But the code beneath (fn first_word()
returns the first word in a string) does not throw a compile time error unless I uncomment the (now commented) println!(). The compile time error only shows when I actually use the variable word within the println!(). Is that supposed to happen?
Also what change would I need to make such that code the returned first word of the string doesn't change no matter what I do with the original string?
I'm new to asking questions on a forum about a language and I'm sorry if the question is a little ambiguously put
fn main() {
let mut s = String::from("Hello world");
let word = first_word(&s);
s.clear();
// println!("the first word is {} ", word);
}
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}