Closed
Description
The string guide distinguishes between String
and &str
but makes no mention of a third type people will come across: str
. &str
is defined as the type which you refer to? Perhaps define str
as the type and mention that in most cases it must be borrowed...
This honestly threw me the first time I saw it. I thought, "what is str
...there's only &str
and String
...".
fn main() {
let str_slice = "str slice";
let mut string = String::new();
// Doesn't work because `str_slice[0..3]` needs a `&`
string = string + str_slice[0..3] + "ing";
println!("{:?}", string); // Would print `string` without the error.
}
Error:
... error ... expected str, found &-ptr
<anon>:5 string = string + str_slice[0..3] + "ing";
^~~~~~~~~~~~~~~
Activity
Manishearth commentedon Jan 12, 2015
Note:
str
is an unsized type, and&str
is simply a pointer to the unsized type (like&Trait
or&[]
). But I agree that the docs could be clearer.jakerr commentedon Jan 29, 2015
The error messages can be quite unfriendly for new users.
I recently saw someone attempt:
The error:
Doesn't mean much to a new user.
What does that mean to users? Is there a valid reason to ever use
str
in code?The std::str doc says
So it's not a valid type? But the error message you gave me said "for the type
str
" ... If it's not valid why doesn't the compiler say so in the error message above, instead of complaining that it's unsized?steveklabnik commentedon Feb 2, 2015
Today, this is the string chapter of the book.
Make note of str in 'more strings' chapter