Skip to content

Commit

Permalink
Rollup merge of rust-lang#92715 - chordtoll:empty-string, r=davidtwco
Browse files Browse the repository at this point in the history
Do not suggest char literal for zero-length strings

PR rust-lang#92507 adds a hint to switch to single quotes when a char is expected and a single-character string literal is provided.

The check to ensure the string literal is one character long missed the 0-char case, and would incorrectly offer the hint.

This PR adds the missing check, and a test case to confirm the new behavior.
  • Loading branch information
matthiaskrgr authored Feb 8, 2022
2 parents f9a710e + 9622a42 commit f830291
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2053,7 +2053,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
if let Some(code) =
code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
{
if code.chars().nth(1).is_none() {
if code.chars().count() == 1 {
err.span_suggestion(
span,
"if you meant to write a `char` literal, use single quotes",
Expand Down
3 changes: 2 additions & 1 deletion src/test/ui/inference/char-as-str-multi.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// When a MULTI-character string literal is used where a char should be,
// When a MULTI/NO-character string literal is used where a char should be,
// DO NOT suggest changing to single quotes.

fn main() {
let _: char = "foo"; //~ ERROR mismatched types
let _: char = ""; //~ ERROR mismatched types
}
10 changes: 9 additions & 1 deletion src/test/ui/inference/char-as-str-multi.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ LL | let _: char = "foo";
| |
| expected due to this

error: aborting due to previous error
error[E0308]: mismatched types
--> $DIR/char-as-str-multi.rs:6:19
|
LL | let _: char = "";
| ---- ^^ expected `char`, found `&str`
| |
| expected due to this

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0308`.

0 comments on commit f830291

Please sign in to comment.