Skip to content

Commit a15cb49

Browse files
committed
rust-lang#91836: Clarify error on casting larger integers to char
1 parent 06a6674 commit a15cb49

File tree

2 files changed

+9
-3
lines changed
  • compiler

2 files changed

+9
-3
lines changed

compiler/rustc_error_codes/src/error_codes/E0604.md

+8-3
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@ Erroneous code example:
66
0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
77
```
88

9-
As the error message indicates, only `u8` can be cast into `char`. Example:
9+
`char` is a Unicode Scalar Value, an integer value from 0 to 0xD7FF and
10+
0xE000 to 0x10FFFF. (The gap is for surrogate pairs.) Only `u8` always fits in
11+
those ranges so only `u8` may be cast to `char`.
12+
13+
To allow larger values, use `char::from_u32`, which checks the value is valid.
1014

1115
```
12-
let c = 86u8 as char; // ok!
13-
assert_eq!(c, 'V');
16+
assert_eq!(86u8 as char, 'V'); // ok!
17+
assert_eq!(char::from_u32(0x3B1), Some('α')); // ok!
18+
assert_eq!(char::from_u32(0xD800), None); // not a USV.
1419
```
1520

1621
For more information about casts, take a look at the Type cast section in

compiler/rustc_typeck/src/check/cast.rs

+1
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
337337
self.expr_ty
338338
)
339339
.span_label(self.span, "invalid cast")
340+
.span_help(self.span, "try `char::from_u32` instead")
340341
.emit();
341342
}
342343
CastError::NonScalar => {

0 commit comments

Comments
 (0)