Skip to content

String guide: make distinction between str and &str #21035

Closed
@mdinger

Description

@mdinger

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 ...".

Problematic case:

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";
                               ^~~~~~~~~~~~~~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions