Skip to content

String/str should not support sliced indexing #21557

@tomjakubowski

Description

@tomjakubowski

A common question from Rust newbies is why String/str don't allow simple indexing, like this:

let foo = "foobar";
let x = foo[0];

The answer has always been that foo[0] is both ambiguous and dangerous given that str is a UTF-8 string: it could be a byte offset returning a char, a byte offset returning a u8, a codepoint index returning a char, etc., each having its own potential pitfalls of panicking or slowness.

For the same reason that foo[0] is not allowed, foo[m..n] and foo[..n] and similar such "sliced" indexing operations shouldn't be allowed.

(It's also a bit strange that both String and str impl these traits; since String is Deref<str>, shouldn't it only be needed on str?)

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