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 objectReal 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 Stringorv 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
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
- E0061this function takes N arguments but M were supplied
- E0412cannot find type in this scope
- E0515cannot return reference to local variable
- E0728await is only allowed inside async functions and blocks
- E0590`break` or `continue` with no label in the condition of a `while` loop
- E0591Per [RFC 401][rfc401], if you have a function declaration `foo`:
- E0606casting `&u8` as `u32` is invalid
- E0618expected function, found
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?