Skip to content

Commit e6e195e

Browse files
fix: diagnostic for casting reference to slice
fixes: rust-lang#118790
1 parent 5ac4c8a commit e6e195e

File tree

3 files changed

+39
-18
lines changed

3 files changed

+39
-18
lines changed

compiler/rustc_hir_typeck/src/cast.rs

+12-18
Original file line numberDiff line numberDiff line change
@@ -576,25 +576,19 @@ impl<'a, 'tcx> CastCheck<'tcx> {
576576
match self.expr_ty.kind() {
577577
ty::Ref(_, _, mt) => {
578578
let mtstr = mt.prefix_str();
579-
if self.cast_ty.is_trait() {
580-
match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
581-
Ok(s) => {
582-
err.span_suggestion(
583-
self.cast_span,
584-
"try casting to a reference instead",
585-
format!("&{mtstr}{s}"),
586-
Applicability::MachineApplicable,
587-
);
588-
}
589-
Err(_) => {
590-
let msg = format!("did you mean `&{mtstr}{tstr}`?");
591-
err.span_help(self.cast_span, msg);
592-
}
579+
match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
580+
Ok(s) => {
581+
err.span_suggestion(
582+
self.cast_span,
583+
"try casting to a reference instead",
584+
format!("&{mtstr}{s}"),
585+
Applicability::MachineApplicable,
586+
);
587+
}
588+
Err(_) => {
589+
let msg = format!("did you mean `&{mtstr}{tstr}`?");
590+
err.span_help(self.cast_span, msg);
593591
}
594-
} else {
595-
let msg =
596-
format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
597-
err.span_help(self.span, msg);
598592
}
599593
}
600594
ty::Adt(def, ..) if def.is_box() => {

tests/ui/cast/cast-to-slice.rs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
"example".as_bytes() as [char];
3+
//~^ ERROR cast to unsized type
4+
5+
let arr: &[u8] = &[0, 2, 3];
6+
arr as [char];
7+
//~^ ERROR cast to unsized type
8+
}

tests/ui/cast/cast-to-slice.stderr

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error[E0620]: cast to unsized type: `&[u8]` as `[char]`
2+
--> $DIR/cast-to-slice.rs:2:5
3+
|
4+
LL | "example".as_bytes() as [char];
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^------
6+
| |
7+
| help: try casting to a reference instead: `&[char]`
8+
9+
error[E0620]: cast to unsized type: `&[u8]` as `[char]`
10+
--> $DIR/cast-to-slice.rs:6:5
11+
|
12+
LL | arr as [char];
13+
| ^^^^^^^------
14+
| |
15+
| help: try casting to a reference instead: `&[char]`
16+
17+
error: aborting due to 2 previous errors
18+
19+
For more information about this error, try `rustc --explain E0620`.

0 commit comments

Comments
 (0)