Casts (v0.2.1)
Explicit type conversion between compatible source and target types.
Overview
Casts convert a value to another type with as. They are useful when changing integer width, signedness, or pointer form.
Because casts are explicit, readers can see where a conversion happens instead of guessing which conversions the compiler inserted.
Use casts close to the boundary that needs them. If the rest of the function can use one clear type, prefer that.
Primary source: syntax/cast/casts.md
Syntax Signatures
var x: s32 = 10;
var y: u32 = x as u32;
var raw: ptr = y as ptr;
Behavior and Use
Narrowing casts can lose information. Check ranges before converting to a smaller type.
Pointer casts should stay in low-level code where the memory layout is understood.
Best Practices
- Check the range before converting to a smaller type.
- Avoid casting back and forth repeatedly.
- Keep cast-heavy code close to the low-level code that needs it.
Numeric Casts
Numeric casts are explicit because they can change representation.
- Casting from a wider integer to a narrower integer can discard high bits.
- Casting between signed and unsigned types changes how the same bits are interpreted.
- Casting between integer and floating-point types can lose precision. Check ranges before relying on the result.
Pointer Casts
Pointer casts should stay near code that knows the memory layout.
- A raw ptr can be converted to a typed pointer when the pointed storage is known to hold that type.
- A typed pointer can be converted to raw ptr for FFI and allocation APIs.
- Do not use casts to bypass type errors in ordinary code. Prefer the correct type at the boundary.
Example
fn toUnsigned(x: s32) u32 @public {
if x < 0 {
return 0;
}
return x as u32;
}