Type Casting

Type Casting

Operator

Name Description
as Allows primitive types to be cast between each other.

Casting

The as operator converts a value of one type to a value of another type. As much as possible, the actual value is preserved, but there are certain value ranges for which that cannot be done.

This can also be used to change the target type of a Raw Pointer value. For example, *const MyStruct can be changed to *const u8.

Valid Casts

Expression Target Type Description
Numerical Numerical Signed integers, unsigned integers, and floating point numbers can be cast between each other.
*mut T *const Y or *mut Y Mutable raw pointers can be cast to constant or mutable raw pointers
*mut T or *const T *const Y Any raw pointer can be cast to a constant raw pointer
*mut T or *const T integer Any raw pointer can be cast to an integer
Integer *const T An integer can be cast to a constant raw pointer

Numerical types: bool i8 i16 i32 i64 u8 u16 u32 u64 f64

Integer types: bool i8 i16 i32 i64 u8 u16 u32 u64

Floating point types: f64

T and Y can be any type.

For raw pointer casts, the goal is to make it as difficult as possible to bypass the declared mutability of a location in memory.

Integer Upcasting

When an integer is cast to an integer with higher bit width the additional bits need to be filled. If the source expression operand is signed, then the upcast will extend the sign bit. If the source expression operand is unsigned, then the upcast will do a zero extend.

Examples

Expression Result Description
1i8 as i32 1 Upcasting from signed to signed will result in the same value.
-1i8 as i32 -1 The negative sign is extended resulting in the same value.
-2i8 as u64 18446744073709551614 When upcasting a signed integer, the sign is extended.
65535u16 as i64 65535 Unsigned integers are upcast by extending zeroes.

Integer Downcasting

When an integer is cast to a type with a smaller bit width, then the extra bits in the source are truncated.

Examples

Expression Result Description
-2i16 as i8 -2 These values are small enough that truncation has no effect.
-5i16 as u8 254 u8 is formed by truncating all but the least significant byte from -5.
-500i16 as i8 12 Truncation converts the negative i16 to a positive i8.

Floating Point to Integer Casting

FP to Int conversion takes the FP value and converts it to an integer value. If the FP value is outside the possible bounds of the target Integer type, then the result is a poison value. Conversion is always done by rounding towards zero.

For more details on poison values, see the LLVM Documentation.

Syntax Rules

EXPR as TYPE

Semantic Rules

S, T: Primitive Type, e: S :- e as T -> T