Email me

Rust errors / Everything else

Rust compiler error · checked with rustc 1.99.0

Rust error E0605: non-primitive cast

What it meansas only converts between primitive types (numbers, bool, char, raw pointers). Everything else needs From/Into, TryFrom, or a method.

What rustc prints

error[E0605]: non-primitive cast: `u8` as `Vec<u8>`
 --> main.rs:4:1
  |
4 | x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
  | ^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object

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.

Why it happens

  • x as String or v as Vec<u8>.
  • Casting between your own structs or enums with data.

How to fix it

1. Use From / Into

let s: String = 42.to_string();
let bytes: Vec<u8> = "hi".into();

2. Use TryFrom when it can fail

let small = u8::try_from(300_u32).unwrap_or(u8::MAX);

Other wordings of this error

non-primitive cast, an `as` expression can only be used to convert between primitive types

E0605Everything else
Activein rustc 1.99.0
8related errors linked below

The compiler team's explanation

An invalid cast was attempted.

Erroneous code examples:

let x = 0u8;
x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`

// Another example

let v = core::ptr::null::<u8>(); // So here, `v` is a `*const u8`.
v as &u8; // error: non-primitive cast: `*const u8` as `&u8`

Only primitive types can be cast into each other. Examples:

let x = 0u8;
x as u32; // ok!

let v = core::ptr::null::<u8>();
v as *const i8; // ok!

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

From rustc --explain E0605 (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 nextE0061: this function takes N arguments but M were suppliedA 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