The Rust Book section on the as operator currently says
The as keyword does basic casting:
let x: i32 = 5;
let y = x as i64;
It only allows certain kinds of casting, however.
What are those certain kinds of allowed casting?
A since-deleted answer here explained that sometimes you need to chain multiple as-casts to accomplish a safe result, that can't be done in a single step. When is that necessary?
I don't think that this is documented very well, but here is some information you might find useful:
A cast
e as Uis valid if one of the following holds:
ehas typeTandTcoerces toU; coercion-castehas type*T,Uis*U_0, and eitherU_0: Sizedor unsize_kind(T) = unsize_kind(U_0); ptr-ptr-castehas type*TandUis a numeric type, whileT: Sized; ptr-addr-casteis an integer andUis*U_0, whileU_0: Sized; addr-ptr-castehas typeTandTandUare any numeric types; numeric-casteis a C-like enum andUis an integer type; enum-castehas typeboolorcharandUis an integer; prim-int-castehas typeu8andUischar; u8-char-castehas type&[T; n]andUis*const T; array-ptr-casteis a function pointer type andUhas type*T, whileT: Sized; fptr-ptr-casteis a function pointer type andUis an integer; fptr-addr-castwhere
&.Tand*Tare references of either mutability, and where unsize_kind(T) is the kind of the unsize info inT- the vtable for a trait definition (e.g.fmt::DisplayorIterator, notIterator<Item=u8>) or a length (or()ifT: Sized).Note that lengths are not adjusted when casting raw slices -
T: *const [u16] as *const [u8]creates a slice that only includes half of the original memory.Casting is not transitive, that is, even if
e as U1 as U2is a valid expression,e as U2is not necessarily so (in fact it will only be valid ifU1coerces toU2).
Quoted from The Rustonomicon: Casts
Here's an exhaustive list of all the true casts. For brevity, we will use * to denote either a *const or *mut, and integer to denote any integral primitive:
- *T as *U where T, U: Sized
- *T as *U TODO: explain unsized situation
- *T as integer
- integer as *T
- number as number
- C-like-enum as integer
- bool as integer
- char as integer
- u8 as char
- &[T; n] as *const T
- fn as *T where T: Sized
- fn as integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With