File tree Expand file tree Collapse file tree 2 files changed +9
-3
lines changed
rustc_error_codes/src/error_codes Expand file tree Collapse file tree 2 files changed +9
-3
lines changed Original file line number Diff line number Diff line change @@ -6,11 +6,16 @@ Erroneous code example:
660u32 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
1621For more information about casts, take a look at the Type cast section in
Original file line number Diff line number Diff 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 => {
You can’t perform that action at this time.
0 commit comments