File tree 2 files changed +9
-3
lines changed
rustc_error_codes/src/error_codes
2 files changed +9
-3
lines changed Original file line number Diff line number Diff line change @@ -6,11 +6,16 @@ Erroneous code example:
6
6
0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
7
7
```
8
8
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.
10
14
11
15
```
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.
14
19
```
15
20
16
21
For 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> {
337
337
self . expr_ty
338
338
)
339
339
. span_label ( self . span , "invalid cast" )
340
+ . span_help ( self . span , "try `char::from_u32` instead" )
340
341
. emit ( ) ;
341
342
}
342
343
CastError :: NonScalar => {
You can’t perform that action at this time.
0 commit comments