Email me

Rust errors / Types and traits

Rust compiler error · checked with rustc 1.99.0

Rust error E0604: only `u8` can be cast as `char`, not `u32`

What it meansA cast to char was attempted on a type other than u8.

What rustc prints

error[E0604]: only `u8` can be cast as `char`, not `u32`
 --> main.rs:3:1
  |
3 | 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
  | ^^^^^^^^^^^^ invalid cast
  |
help: consider using `char::from_u32` instead
  |
3 - 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
3 + char::from_u32(0u32); // error: only `u8` can be cast as `char`, not `u32`
  |

Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.

E0604Types and traits
Activein rustc 1.99.0
7related errors linked below

The compiler team's explanation

A cast to char was attempted on a type other than u8.

Erroneous code example:

0u32 as char; // error: only `u8` can be cast as `char`, not `u32`

char is a Unicode Scalar Value, an integer value from 0 to 0xD7FF and 0xE000 to 0x10FFFF. (The gap is for surrogate pairs.) Only u8 always fits in those ranges so only u8 may be cast to char.

To allow larger values, use char::from_u32, which checks the value is valid.

assert_eq!(86u8 as char, 'V'); // ok!
assert_eq!(char::from_u32(0x3B1), Some('α')); // ok!
assert_eq!(char::from_u32(0xD800), None); // not a USV.

For more information about casts, take a look at the Type cast section in The Reference Book.

From rustc --explain E0604 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.

Related errors

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0308: mismatched typesA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ