Considering the following program:
fn main() {
let s = String::from("helloworld");
// This works fine
println!("The first word is: {}", first_word(&s));
// This won't compile
println!("The first word is: {}", first_word(&s[..]));
// This works fine
println!("The first word is: {}", first_word1(&s));
// This works fine
println!("The first word is: {}", first_word1(&s[..]));
}
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
}
fn first_word1(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
It seems that for a &str parameter, you can use either a &String or a &str as argument, but for a &String parameter, only &String is allowed. It also seems that if a function returns &str in its signature, it can return either a &String or a &str, the caller of the function won't see any difference.
So my question is, what is the difference between &String and &str, in parameter types and return types of rust function signatures?