Casts (v0.2.1)

Explicit type conversion between compatible source and target types.

Latest

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

Numeric Casts

Numeric casts are explicit because they can change representation.

Pointer Casts

Pointer casts should stay near code that knows the memory layout.

Example

fn toUnsigned(x: s32) u32 @public {
    if x < 0 {
        return 0;
    }
    return x as u32;
}

Back to language reference