-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
request: improve string indexing error message #56740
Comments
We should add a Lines 63 to 79 in bd47d68
This will cause an extra Beyond changing the code, you will also need to add a new test case with the repro case above and update all of the tests (running |
I would like to work on this. |
Possible proposed output from #57055:
|
Better error note on unimplemented Index trait for string fixes rust-lang#56740 I've tried to compile suggestion from comments in the issue rust-lang#56740, but unsure of it. So I'm open to advice :) Current output will be like this: ```rust error[E0277]: the type `str` cannot be indexed by `{integer}` --> $DIR/str-idx.rs:3:17 | LL | let c: u8 = s[4]; //~ ERROR the type `str` cannot be indexed by `{integer}` | ^^^^ `str` cannot be indexed by `{integer}` | = help: the trait `std::ops::Index<{integer}>` is not implemented for `str` = note: you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings> error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. ``` `x.py test src/test/ui` succeeded and I've also tested output manually by compiling the following code: ```rust fn _f() { let s = std::string::String::from("hello"); let _c = s[0]; let s = std::string::String::from("hello"); let mut _c = s[0]; let s = "hello"; let _c = s[0]; let s = "hello"; let mut _c = &s[0]; } ``` Not sure if some docs should be changed too. I will also fix error message in the [Book :: Indexing into Strings](https://github.com/rust-lang/book/blob/db53e2e3cdf77beac853df6f29db4b3b86ea598c/src/ch08-02-strings.md#indexing-into-strings) if that PR will get approved :)
The following buggy code:
produces the error:
This is usefully documented in TRPL (ch08-02-strings), but that is not easily discoverable from the error. Meanwhile, the error itself is a natural one that programmers from many languages (C, C++, etc) might run into. Speaking as someone who spent some time assuming that the issue was related to slices/references/usize (i.e. various new, Rust-specific concepts), not strings and UTF-8 encoding, I wonder whether a special case might be produced, replacing error E0277, when the types involved are specifically strings/strs and integers.
Meta
rustc --version --verbose
:The text was updated successfully, but these errors were encountered: